The PHP code below randomly selects a color from an array. If the randomly selected color is blue, it returns the array; if the randomly selected color is not blue, it removes that color and recursively executes the function until it randomly selects the blue color and the returns the array.
$reduce_unwanted_colors = function (&$arr) use (&$reduce_unwanted_colors)
{
$rand_key = array_rand($arr);
if ($arr[$rand_key] == 'blue')
{
return $arr;
}
else
{
unset($arr[$rand_key]);
$reduce_unwanted_colors($arr);
}
};
$arr = ['red', 'green', 'blue', 'orange', 'yellow'];
print_r($reduce_unwanted_colors($arr));
What is weird is that, the print_r()
is showing either the intact array or nothing (an empty string maybe?).
I'm not sure whether the unset()
is accidentally removing all array elements or not. Even if it is, I think the print_r()
should still show Array ( )
rather than showing nothing.
What I was expected from the print_r()
is an array which contains at least an element (the blue color). I cannot figure out what's going on.
Please note that the code is just an example simply for illustration's sake.
Since you're passing $arr
by reference, you don't need to return anything from the function; modifying the array in the body is sufficient. This also means you don't have to do anything when you find the blue
element; just recurse when the current element is not blue
.
$reduce_unwanted_colors = function (&$arr) use (&$reduce_unwanted_colors)
{
$rand_key = array_rand($arr);
if ($arr[$rand_key] != 'blue') {
unset($arr[$rand_key]);
$reduce_unwanted_colors($arr);
}
};
$arr = ['red', 'green', 'blue', 'orange', 'yellow'];
$reduce_unwanted_colors($arr);
print_r($arr);
Demo of lots of random output on 3v4l.org