在php数组中进行简单的键搜索

I have a simple multidimensional array, like so:

$arr1 = array(3,5,array(4,"foo", array("bar","qux"=>"id")));

Then the recursive function,

function getVal($arr){
    foreach($arr as $key=>$val){
      if($key=="qux"){
        echo $val."<br>";
      }elseif(is_array($val)){
        getVal($val);
      }
    }
}

Then finally, calling the function for the first time

getVal($arr1);

However, it outputs

3
4
bar
id

As opposed to only "id". Where did I go wrong?

Some of your keys are numbers, which means you're doing 0 == 'qux', which in PHP-land evaluates to true (qux gets converted to integer 0, and obviously 0==0 is true). You need to use ===, which compares value AND type.

Try this:

<?php
$arr1 = array(3,5,array(4,"foo", array("bar","qux"=>"id")));
function getVal($arr){
    foreach($arr as $key=>$val){
      if($key==="qux"){
        echo $val."<br>";
      }elseif(is_array($val)){
        getVal($val);
      }
    }
}
getVal($arr1);
?>