Last active
May 9, 2017 18:41
-
-
Save jeromegamez/a8cdd9960bfc4c70f152 to your computer and use it in GitHub Desktop.
PHP: array_keys_exist() - like`array_key_exist(), but for multiple keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NICE!
Something similar I have seen in OptionResolver component from Symfony