PHP
Efficiently Checking for Multiple Keys in a PHP Associative Array
Learn how to write a concise and efficient function to verify if an associative array contains all of a specified list of keys using `array_key_exists()`.
<?php
/**
* Checks if an associative array contains all specified keys.
*
* @param array $array The associative array to check.
* @param array $keys An array of keys to search for.
* @return bool True if all keys exist, false otherwise.
*/
function arrayContainsAllKeys(array $array, array $keys): bool
{
foreach ($keys as $key) {
if (!array_key_exists($key, $array)) {
return false;
}
}
return true;
}
// Example Usage:
$userData = [
'id' => 1,
'name' => 'John Doe',
'email' => '[email protected]',
'role' => 'admin'
];
$requiredKeys = ['id', 'name', 'email'];
$missingKeySet = ['id', 'address', 'phone'];
$emptyArray = [];
echo "Checking userData for [" . implode(', ', $requiredKeys) . "]: ";
var_dump(arrayContainsAllKeys($userData, $requiredKeys)); // Expected: true
echo "Checking userData for [" . implode(', ', $missingKeySet) . "]: ";
var_dump(arrayContainsAllKeys($userData, $missingKeySet)); // Expected: false
echo "Checking emptyArray for [" . implode(', ', $requiredKeys) . "]: ";
var_dump(arrayContainsAllKeys($emptyArray, $requiredKeys)); // Expected: false
echo "Checking userData for []: ";
var_dump(arrayContainsAllKeys($userData, [])); // Expected: true (no keys required)
$product = ['name' => 'Book', 'price' => 20];
$keysToCheck = ['name', 'price', 'description'];
echo "Checking product for [" . implode(', ', $keysToCheck) . "]: ";
var_dump(arrayContainsAllKeys($product, $keysToCheck)); // Expected: false
?>
How it works: This simple yet powerful function checks if an associative array contains all the keys specified in a list. It iterates through the list of required keys, using `array_key_exists()` for efficient checking. If any key is not found, it immediately returns `false`; otherwise, if all keys are present, it returns `true`. This is invaluable for validating data structures, especially when dealing with incoming request data or configuration arrays.