9

I am currently using the following:

    $a = array('foo' => 'bar', 'bar' => 'foo');

    if(isset($a['foo']) && isset($a['bar'])){
      echo 'all exist';
    }

However, I will have several more array keys than foo and bar that I must check for. Is there a more efficient way to check for each required key than adding an isset for each required entry?

1
  • ignore that possible duplicate flag; i just realized the subtle difference. Commented Apr 21, 2014 at 23:23

3 Answers 3

26

You can combine them in a single isset() call:

if (isset($a['foo'], $a['bar']) {
    echo 'all exist';
}

If you have an array of all the keys that are required, you can do:

if (count(array_diff($required_keys, array_keys($a))) == 0) {
    echo 'all exist';
}
Sign up to request clarification or add additional context in comments.

4 Comments

Getting an error: Can't use function return value in write context for the line if (empty(array_diff($required_keys, array_keys($a))) {.
Apparently empty() requires its argument to be a variable, not an expression. Changed to use count().
Regards empty(): empty($x) is equivalent to ! isset($x) || !$x; an expression cannot be "unset", hence the restriction (which is/will be relaxed in PHP 5.5). So you could just say if ( ! array_diff(...) ), count(...) == 0 is probably more readable when dealing with arrays.
Just out of curiosity, I compared count(array_diff(...)) == 0 vs array_diff(...) == [] and was able to repeatably shave off 0.3 seconds over 1000000 iterations with the latter. This translates into almost absolutely no performance gains. I opted for empty array equals empty array because it matches my coding style, but for anyone else curious, all comes down to preference.
1

You could create an array of all the entries you want to check, then iterate over all of them.

$entries = array("foo", "bar", "baz");
$allPassed = true;

foreach($entries as $entry)
{
    if( !isset( $a[$entry] ) )
    {
        $allPassed = false;
        break;
    }
}

If $allPassed = true, all are good - false means one or more failed.

Comments

0

Probably the cleanest is

if (array_diff(['foo', 'bar'], array_keys($a))) === []) {
    echo 'all exist';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.