I want to be able to check if a certain key exists within my array. I have an array and I'm merging multiple arrays from mysql. What would be the best way to do so?
for example
Array
(
[0] => Array
(
[id] => 3
[comments] => comment text
)
[1] => Array
(
[id] => 3
[comments] => comment text
)
[2] => Array
(
[idMenu] => 1
[names] => text
)
[3] => Array
(
[idMenu] => 3
[names] => names text
)
)
So I'm trying to see if this array has comments and/or names.
do i have to do an if statement?
Thanks
Assuming that your parent array will always return bunch of children arrays...
foreach ($parentArray as $childArray) {
if (array_key_exists("comments", $childArray) { return true; }
if (array_key_exists("names", $childArray) { return true; }
}
Now, that merely checks to see if the parent has a child array with one of those keys.. Actually checking the value to see if it is empty would take a little more code, but this should get you going in the right direction.
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)