0

I have a multidimentional array (MyArray), and want to "linearize" it to a string. So I try with this recursive function:

function RecursiveFunction($TheArray){
    foreach($TheArray as $key => $value){
        if(is_array($value)){
            $RecursiveOutput.="(".$key.")";
            RecursiveFunction($value); //-->this does't seem to work
        } else {
            $RecursiveOutput.="(".$value.")";
        }
    }
    return $RecursiveOutput;
}
echo RecursiveFunction($MyArray);

However, I'm getting the keys from the first level of the array only: the recursive recall doesn't seem to work. Can anyone spot the problem?

9
  • 2
    You do not pick the return value of the inner function call, which you need to do. Commented Nov 12, 2017 at 12:18
  • You are returning $RecursiveOutput but you aren't catching the return value. Commented Nov 12, 2017 at 12:19
  • 1
    Try this $RecursiveOutput .= "(".$key.")"."(".RecursiveFunction($value).")"; Commented Nov 12, 2017 at 12:21
  • Or you could pass the variable by reference? Commented Nov 12, 2017 at 12:21
  • @RisulIslam thats it! $RecursiveOutput .= "(".$key.")"."(".RecursiveFunction($value).")";. Post as an answer for accepting. Thanks a lot! Commented Nov 12, 2017 at 12:24

1 Answer 1

1

You are returning $RecursiveOutput but you aren't catching the return value. Try this

$RecursiveOutput .= "(". $key .")(". RecursiveFunction($value) .")";
Sign up to request clarification or add additional context in comments.

Comments

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.