Search code examples
phprecursionphp-5.3

recursively add elements to array and return new array


Let's say I have an array like this:

$my_array = array(1, 2, 3, 4, array(11, 12, 13, 14), 6, 7, 8, array(15, 16, 17, 18), 10);

I want to build a recursive function that returns an array which contains all the even numbers from my_array. I tried something like:

function get_even_numbers($my_array)
{
    $even_numbers = array();

    foreach($my_array as $my_arr)
    {
        if(is_array($my_arr)
        {
            get_even_numbers($my_arr);

            foreach($my_arr as $value)
            {
                if($value % 2 == 0)
                {
                    $even_numbers[] = $value;
                }
            }
        }
    }

    return even_numbers;
}

But it doesn't works.

Thank you


Solution

  • It's simple:

    1. Check if the input you get into the function is an array.
    2. If it is, that means you have to loop over the values of the array, and call your function (so it is recursive)
    3. Otherwise, just check if the value coming in is even, and add it to an array to return.

    That, in PHP, looks like:

    function recursive_even( $input) {
        $even = array();
        if( is_array( $input)) {
            foreach( $input as $el) {
                $even = array_merge( $even, recursive_even( $el));
            }
        }
        else if( $input % 2 === 0){
             $even[] = $input;
        }
        return $even;
    }