VIDesignz VIDesignz - 3 months ago 11
PHP Question

How to "skip" itteration when building a new array using recursion

I am stuck on something that might be very simple.

I am creating a new array by looping through an existing array using a recursion function yet I can not seem to get the values to stick to the new array. The function, in the end, will be a bit more complex, but for now I need some help.

I have tried soooo many ways to get this to work but I am at a loss right now.

Here is my php function

function recursive($array) {

$newArray = array();

foreach($array as $key => $value) {

if(is_array($value)){
recursive($value);
}else{
$newArray[] = $value;
}

}

return $newArray;

}


As is, the new array never gets filled...BUT, if I change this line...

recursive($value); // Why can't I just call the recursive function here?


...to...

$newArray[] = recursive($value); // Instead of having to set a new value to the new array?


everything works properly...except that my goal was to create a flat array with only the values.

So my question is, why is it necessary to set a new array value in order to call the recursive function again? Ideally, I want to skip setting a new array value if the value is an array and just continue the loop through the original array.

Any help in explaining would be great!

Answer

Use array_merge:

function recursive($array) {

    $newArray = array();

    foreach($array as $key => $value) {

        if(is_array($value)){
            $newArray = array_merge($newArray, recursive($value));                              
        }else{
            $newArray[] = $value;
        }   

    }

    return $newArray;

}

...or you could use special operator:

function recursive($array) {

    $newArray = array();

    foreach($array as $key => $value) {

        if(is_array($value)){
            $newArray += recursive($value);                              
        }else{
            $newArray[] = $value;
        }   

    }

    return $newArray;

}

...or pass a variable by reference like this:

function recursive($array, &$newArray = null) {

    if (!$newArray) {
        $newArray = array();
    }

    foreach($array as $key => $value) {

        if(is_array($value)){
            recursive($value, $newArray);                              
        }else{
            $newArray[] = $value;
        }   

    }

    return $newArray;   
}