Skip to content

Instantly share code, notes, and snippets.

@jeromegamez
Last active May 9, 2017 18:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeromegamez/a8cdd9960bfc4c70f152 to your computer and use it in GitHub Desktop.
Save jeromegamez/a8cdd9960bfc4c70f152 to your computer and use it in GitHub Desktop.
PHP: array_keys_exist() - like`array_key_exist(), but for multiple keys
<?php
/**
* Returns TRUE if the given keys are all set in the array. Each key can be any value possible for an array index.
*
* @see array_key_exists()
*
* @param array $array An array with keys to check.
* @param string[] $keys Keys to check.
* @param mixed $missing Reference to a variable that that contains the missing keys.
*
* @return bool true if all given keys exist in the given array, false if not
*/
public static function array_keys_exist(array $array, array $keys, &$missing = null) {
$missing = array_diff($keys, array_keys($array));
return array_reduce($keys, function($carry, $key) use ($array) {
return $carry && array_key_exists($key, $array);
}, true);
}
$array = ['foo' => 'value'];
$requiredKeys = ['foo', 'bar', 'baz'];
if (array_keys_exist($array, $requiredKeys, $missing)) {
echo "All keys are set.";
} else {
printf("Keys are missing: %s", implode(', ', $missing));
}
// Output:
// Keys are missing: bar, baz
@iamtankist
Copy link

NICE!

Something similar I have seen in OptionResolver component from Symfony

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment