September 10, 2013

Check whether array has keys that don't match a list

Donny P’s Question:

What is the easiest way to check if an has array keys that don’t match a particular list?

$a = array(
  [ignore_me] => "blah blah blah",
  [name] => "Don"
);

does_array_have_non_ignored_entries($a); // returns true

I can think of a ton of ways to write this function, didn’t know if PHP has a quick solution. Best one I have is this:

$length = count($a);
$ignored_entry = (in_array($a, 'ignore_me') ? 1 : 0;
if ($length - $ignored_entry > 0) {...}

How about this?

$count = isset($a['ignore_me']) ? count($a) -1 : count($a);

Substract 1, if that key is found, else use the full length.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!