Mooseman Mooseman - 1 year ago 36
PHP Question

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
that I must check for. Is there a more efficient way to check for each required key than adding an
for each required entry?

Answer Source

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