I need to find the key of a value in a multidimensional array
-
Couldn't you loop through all the elements and check each one for equality to the given value? – APerson Sep 24 '14 at 19:03
-
This is multidimensional I don´t even know the number of dimensions – Marcelo Noronha Sep 24 '14 at 19:04
-
2http://stackoverflow.com/questions/4128323/in-array-and-multidimensional-array – Sujit Agarwal Sep 24 '14 at 19:08
-
Search before you ask :) – Sujit Agarwal Sep 24 '14 at 19:12
3 Answers
Search key
So if you know the value, I guess you are looking for the $key. Then use array_search:
$array = array(0 => 'value1', 1 => 'value2', 2 => 'value3', 3 => 'red');
$key = array_search('value2', $array); // 2
If it is a multidimentional array use this function:
function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
In array?
If you want to know if a value is in the array then use the function in_array. With the array above:
if (in_array("value1", $array)) {
echo "value1 is in the array";
}
If it is a multidimentional array then use:
function in_multiarray($elem, $array)
{
$top = sizeof($array) - 1;
$bottom = 0;
while($bottom <= $top)
{
if($array[$bottom] == $elem)
return true;
else
if(is_array($array[$bottom]))
if(in_multiarray($elem, ($array[$bottom])))
return true;
$bottom++;
}
return false;
}

- 1,654
- 12
- 15
-
That´s nice but I´m affraid I don´t know how many dimensions? It´s a multidimensional array, don´t know how many dimensions – Marcelo Noronha Sep 24 '14 at 19:06
-
2
-
1
You don't have to know or care how many dimensions. The multidimensional example in the "Search Key" section of Adam Sinclair's answer will crawl the entire geography of the array, discovering the shape as it goes and forgetting the parts it's done with that didn't yield what you seek.

- 94
- 1
- 5
Firstly you can use in_array/is_array function to search a value in an array but in_array doesn't work for multidimensional array so it would be better searching something with foreach loop specially when its multi dimensinoal array. here's a function from the php manual that works for multi dimensional array and it works recursively so it doesn't matter how deep your input array is.
function myInArray($array, $value, $key){
//loop through the array
foreach ($array as $val) {
//if $val is an array cal myInArray again with $val as array input
if(is_array($val)){
if(myInArray($val,$value,$key))
return true;
}
//else check if the given key has $value as value
else{
if($array[$key]==$value)
return true;
}
}
return false;
}

- 534
- 5
- 14