Check if specific array key exists in multidimensional array - PHP
I played with your code to get it working :
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;
}
array_key_exists()
is helpful.
Then something like this:
function multiKeyExists(array $arr, $key) {
// is in base array?
if (array_key_exists($key, $arr)) {
return true;
}
// check arrays contained in this array
foreach ($arr as $element) {
if (is_array($element)) {
if (multiKeyExists($element, $key)) {
return true;
}
}
}
return false;
}
Working example: http://codepad.org/GU0qG5su
Here is a one line solution:
echo strpos(json_encode($array), $key) > 0 ? "found" : "not found";
This converts the array to a string containing the JSON equivalent, then it uses that string as the haystack argument of the strpos() function and it uses $key as the needle argument ($key is the value to find in the JSON string).
It can be helpful to do this to see the converted string: echo json_encode($array);
Be sure to enclose the needle argument in single quotes then double quotes because the name portion of the name/value pair in the JSON string will appear with double quotes around it. For instance, if looking for 22 in the array below then $key = '"22"'
will give the correct result of not found in this array:
$array =
Array (
21 => Array ( ),
24 =>
Array (
522 => Array ( ),
25 =>
Array (
26 => Array ( )
)
)
);
However, if the single quotes are left off, as in $key = "22"
then an incorrect result of found will result for the array above.
EDIT: A further improvement would be to search for $key = '"22":';
just incase a value of "22"
exists in the array. ie. 27 => "22"
In addition, this approach is not bullet proof. An incorrect found could result if any of the array's values contain the string '"22":'