0

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?

1
  • Try $key === "qux" Commented Nov 25, 2015 at 19:23

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a ton! Thanks for the explanation! Have to wait 9 minutes to accept the answer though.
0

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);
?>

2 Comments

Thanks Manikiran. I'll select @Marc B's answer though because of the explaination.
No worries, I am still a beginner trying to improve my skills.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.