php check if array key code example
Example 1: php key exists
// Here's our fruity array
$fruits = ['apple', 'pear', 'banana'];
// Use it in an `if` statement
if (array_key_exists("banana", $fruits)) {
// Do stuff because `banana` exists
}
// Store it for later use
$exists = array_key_exists("peach", $fruits);
Example 2: keys of array exist in array
function findKey($array, $keySearch)
{
foreach ($array as $key => $item) {
if ($key == $keySearch) {
echo 'yes, it exists';
return true;
} elseif (is_array($item) && findKey($item, $keySearch)) {
return true;
}
}
return false;
}