recursively add elements to array and return new array
10,497
Solution 1
It's simple:
- Check if the input you get into the function is an array.
- If it is, that means you have to loop over the values of the array, and call your function (so it is recursive)
- 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;
}
Solution 2
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;
}
Author by
user765368
Updated on October 09, 2022Comments
-
user765368 over 1 year
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