Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 509
user765368 Avatar asked Jun 12 '26 01:06

user765368


1 Answers

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;
}
like image 177
nickb Avatar answered Jun 14 '26 16:06

nickb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!