Tag Archives: array

PHP Associative Array – Does It Have All The Keys?

It’s not an uncommon programming task to want to check that an associative array (an array with keys) contains all the keys you expect. This is useful when passing an associative array to another function, which needs to check that everything is present before continuing (or at least fail/return fast if they don’t).

PHP doesn’t have a built-in function to compare keys in two array natively. array_key_exists() only looks for a single key – which isn’t quite what I needed here.

However you can build this function from a clever use of two other native functions:

<?php

function array_keys_exists(array $keys_to_be_present, array $arr) {
   return !array_diff_key(array_flip($keys_to_be_present), $arr);
}

This simple function takes a standard array of terms ($keys_to_be_present), which will need to be present as keys in the associative array ($arr) for it to return true.

This is how you’d use it:

<?php

$keys_needed = ['apples', 'pears'];

$array_under_test_1 = ['apples' => 24, 'pears' => 65];
$array_under_test_2 = ['apples' => 42, 'bananas' => 34];

// Will return bool(true)
var_dump(array_keys_exists($keys_needed, $array_under_test_1));

// Will return bool(false)
var_dump(array_keys_exists($keys_needed, $array_under_test_2));

// The function
function array_keys_exists(array $keys_to_be_present, array $arr) {
   return !array_diff_key(array_flip($keys_to_be_present), $arr);
}

So, how does this work? It utilises two functions:

The native function array_flip() converts the $keys_to_be_present array into an associative array:

<?php

$keys_needed = ['apples', 'pears'];

var_dump(array_flip($keys_needed));

// Prints
// array(2) {
//   ["apples"]=>
//   int(0)
//   ["pears"]=>
//   int(1)
// }

Then the array_diff_key() function compares the keys from two arrays and returns the difference. As the array_diff_key() function returns an array containing all the entries from array whose keys are absent from all of the other arrays – we need to negate (!) this value, so that a ‘no differernce’ (empty set) returns from our function as ‘true’.