PHP
Check if an Array Contains All Elements
Verify if a PHP array contains all elements from another array, useful for permission checks, subset validation, or ensuring required items are present.
<?php
/**
* Checks if a haystack array contains all needles.
* @param array $haystack The array to search within.
* @param array $needles The array of elements to find.
* @return bool True if all needles are found in haystack, false otherwise.
*/
function array_contains_all(array $haystack, array $needles): bool
{
foreach ($needles as $needle) {
if (!in_array($needle, $haystack)) {
return false;
}
}
return true;
// Alternative using array_diff (less readable for simple check):
// return empty(array_diff($needles, $haystack));
}
$userPermissions = ['read', 'write', 'delete', 'admin'];
$requiredPermissions = ['read', 'write'];
$missingPermissions = ['execute', 'sudo'];
if (array_contains_all($userPermissions, $requiredPermissions)) {
echo "User has all required permissions (read, write).
";
} else {
echo "User does NOT have all required permissions (read, write).
";
}
if (array_contains_all($userPermissions, $missingPermissions)) {
echo "User has all missing permissions (execute, sudo).
";
} else {
echo "User does NOT have all missing permissions (execute, sudo).
";
}
/*
Output:
User has all required permissions (read, write).
User does NOT have all missing permissions (execute, sudo).
*/
?>
How it works: This snippet provides a function `array_contains_all` that determines whether all elements from one array (`needles`) are present in another array (`haystack`). It iterates through each 'needle' and uses `in_array` to check its existence in the 'haystack'. If any 'needle' is not found, the function immediately returns `false`. If the loop completes, all 'needles' were found, and it returns `true`. This is useful for validating collections or checking prerequisites.