-1

I need to find the key of a value in a multidimensional array

Marcelo Noronha
  • 757
  • 1
  • 10
  • 25

3 Answers3

2

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;
}
Adam Sinclair
  • 1,644
  • 10
  • 15
0

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.

Niali
  • 54
  • 5
0

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;

}

monirz
  • 474
  • 5
  • 14