1

So I'm trying to create a recursive flattenArray function that will take an array (with an unknown number of elements and sub-arrays (with possibly more sub-arrays).

Here's the PHP code I'm having trouble with:

<?php
// Javascript Array [ [1,2,3],[[[4]]],[5],[6],[[7,8,[9]]] ]
// Equivalent PHP Array:   
$sampleArray = Array(
    Array(1,2,3),
    Array(
        Array(
            Array(4)
        )
    ),
    Array(5),
    Array(6),
    Array(
        Array(
            7,
            8,
            Array(9)
        )
    )
);

$finishedArray = Array();

function flattenArray($array){
    foreach ($array as $key => $value) {
        if(is_array($value)){
            flattenArray($value);
        } else {
            $finishedArray[] = $value;
            echo "<br> ".$value." | ";
            print_r($finishedArray);
        }
    }
}

flattenArray($sampleArray);

echo "<br><br>FinishedArray: <br>";
print_r($finishedArray);
?>

I get this output:

1 | Array ( [0] => 1 ) 
2 | Array ( [0] => 1 [1] => 2 ) 
3 | Array ( [0] => 1 [1] => 2 [2] => 3 ) 
4 | Array ( [0] => 4 ) 
5 | Array ( [0] => 5 ) 
6 | Array ( [0] => 6 ) 
7 | Array ( [0] => 7 ) 
8 | Array ( [0] => 7 [1] => 8 ) 
9 | Array ( [0] => 9 ) 

FinishedArray: 
Array ( )

For some reason it resets the $finishedArray. What am I doing wrong here?

1 Answer 1

2

Seems you need to read up on variable scope. There are 2 variables called $finishedArray - one in the main script, and another within the function. Probably the simplest solution would be to pass it via reference:

function flattenArray($array, &$finishedArray){
    foreach ($array as $key => $value) {
        if(is_array($value)){
            flattenArray($value, $finishedArray);
        } else {
            $finishedArray[] = $value;
        }
    }
}

$finishedArray = Array();
flattenArray($sampleArray, $finishedArray);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I even found a simpler fix after seeing your reply: I put "global $finishedArray;" between "function flattenArray($array){" and the foreach statement. Worked like a charm!

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.