I need recursive function to add element into an array. This is my code:
$array_final = array(); $counter = 1; function get_previuos_levels($first_available_place_x, $first_available_place_y, $array_final , $counter) { $new_x = $first_available_place_x-1; $devider = $first_available_place_y/3; $new_y = ceil($devider); //echo $new_x; //echo '<br>'; //echo $new_y; if($new_x > 1) { $array_final['value'][$counter] = $new_x . ' - ' . $new_y; $counter++; get_previuos_levels($new_x, $new_y, $array_final , $counter); } return $array_final; } $result = get_previuos_levels(3, 5, $array_final , $counter); echo '<pre>'; print_r($result ); echo '</pre>';
Basically, if I echo $new_x and $new_y, I get what I’m expecting. Problem is my $result array, it gives me only first item (2 -2) but second is missing (1 -1). I guess problem is with adding item into array but cannot find the problem.
Advertisement
Answer
I found solution if somebody need.
$array_final = array(); $counter = 1; function get_previuos_levels($first_available_place_x, $first_available_place_y) { $new_x = $first_available_place_x-1; $devider = $first_available_place_y/3; $new_y = ceil($devider); $array_key = 1; for($value = $new_x; $value > 0; $value--) { $array_final['x_coor'][$array_key] = $value; $array_final['y_coor'][$array_key] = $new_y; $devider = $new_y/3; $new_y = ceil($devider); $array_key++; } return $array_final; } $result = get_previuos_levels($first_available_place_x, $first_available_place_y); echo '<pre>'; print_r($result); echo '</pre>';