Mooseman
Mooseman

Reputation: 18891

Check if all of several PHP array keys exist

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?

Upvotes: 9

Views: 7477

Answers (3)

Johnny Vietnam
Johnny Vietnam

Reputation: 316

Probably the cleanest is

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

Upvotes: 0

Barmar
Barmar

Reputation: 780949

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';
}

Upvotes: 26

Surreal Dreams
Surreal Dreams

Reputation: 26380

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.

Upvotes: 1

Related Questions