php check if array key exists and has value code example
Example 1: php key exists
$fruits = ['apple', 'pear', 'banana'];
if (array_key_exists("banana", $fruits)) {
}
$exists = array_key_exists("peach", $fruits);
Example 2: php array index exists
$fruits = ['apple', 'pear', 'banana'];
if (array_key_exists("banana", $fruits)) {
}
$exists = array_key_exists("peach", $fruits);
return array_key_exists("pineapple", $fruits);
Example 3: php key in array exists
<?php
$search_array = array('first' => null, 'second' => 4);
isset($search_array['first']);
array_key_exists('first', $search_array);
?>
Example 4: 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;
}