I pulled this function from the manual. It’s a recursive version of array_key_exists(). Since it’s recursive it doesn’t matter how deeply the keys are buried in the array. This function doesn’t tell you where the key may be found — only if it exists.
function array_key_exists_r($needle, $haystack)
{
$result = array_key_exists($needle, $haystack);
if ($result) return $result;
foreach ($haystack as $v) {
if (is_array($v)) {
$result = array_key_exists_r($needle, $v);
}
if ($result) return $result;
}
return $result;
}
Using your array:
<?php
function array_key_exists_r($needle, $haystack)
{
$result = array_key_exists($needle, $haystack);
if ($result) return $result;
foreach ($haystack as $v) {
if (is_array($v)) {
$result = array_key_exists_r($needle, $v);
}
if ($result) return $result;
}
return $result;
}
$arr = array
(
array
(
'id' => 3,
'comments' => 'comment text'
),
array
(
'id' => 3,
'comments' => 'comment text'
),
array
(
'idMenu' => 1,
'names' => 'text'
),
array
(
'idMenu' => 3,
'names' => 'names text'
)
);
var_dump(array_key_exists_r('comments', $arr));
var_dump(array_key_exists_r('names', $arr));
var_dump(array_key_exists_r('bob', $arr));
?>
Output:
bool(true)
bool(true)
bool(false)