Recursive Function in PHP

PHP Recursive Function
PHP also supports recursive function call like C/C++. In such case, we call current function within function. It is also known as recursion.

Like most programming languages that support functions, PHP lets you write recursive functions. In this tutorial, we’ll explore the concept of recursion in PHP, and discover how to create recursive functions for various tasks.

If the function keeps calling itself, how does it know when to stop? You set up a condition, known as a base case. Base cases tell our recursive call when to stop, otherwise it will loop infinitely.

Let’s write a recursive function to display the numbers.

Example : Printing number

<?php
function display($number) {
//If the number is less or equal to 5.
if($number<=5){
echo “$number <br/>”;
display($number+1);
}
}
//Set our start number to 1.
display(1);
?>

Output:

1
2
3
4
5

The code above is pretty simple. Basically, the function checks to see if the number is less than 5. If the number is less than 5, then we increment the number and call the function again. This process is repeated until the number has reached 5.

If you have any query or suggestions, feel free to ask me via the comment section below.

Leave a Reply