In this post, you will learn about the recursion function in PHP With examples.
PHP also supports recursive function call like C, C++. The recursion function continues until some condition is met to stop it.
A function is recursive if it calls itself and reaches a stop condition.
Recursive function With examples
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php function show($num) { if($num<=10){ echo "$num <br/>"; show($num+1); } } show(1); ?> |
Output-
1 2 3 4 5 6 7 8 9 10 | 1 2 3 4 5 6 7 8 9 10 |
A recursive function is not good to use in PHP coding, sometimes if we never maintain the base value, then it may go for infinite, So it will be good if we can use the PHP loop.
Example of an infinite loop, when missing the base value.
1 2 3 4 5 6 7 8 9 10 | <?php function countdown($num_arg) { print("Number is $num_arg<br>"); countdown($num_arg - 1); } countdown(10); ?> |
Maintain the base value in the above code.
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php function countdown($num_arg) { if($num_arg > 0) { print("Number is $num_arg<br>"); countdown($num_arg - 1); } } countdown(10); ?> |