2

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

4
  • So what's your question? You know what you want to do, so go and do it. Commented Apr 23, 2013 at 0:48
  • Why do you want this function to be recursive? Commented Apr 23, 2013 at 0:49
  • for loop is better for this input Commented Apr 23, 2013 at 0:50
  • Still no question (or code). Commented Apr 23, 2013 at 0:51

2 Answers 2

8

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;
}
Sign up to request clarification or add additional context in comments.

Comments

4

Unless it is a thought exercise for your own edification, implementing a recursive function isn't required for this task, which can accomplished instead by using the higher-order, built-in PHP function, array_walk_recursive.

$res = array();
array_walk_recursive($my_array, function($a) use (&$res) { if ($a % 2 == 0) { $res[] = $a; } });

Of course, this could be wrapped in a function:

function get_even_numbers($my_array) {
  $res = array();
  array_walk_recursive($my_array, function($a) use (&$res) { if ($a % 2 == 0) { $res[] = $a; } });
  return $res;
}

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.