What is a RECURSIVE Function in PHP?

RECURSIVE Function in PHP?

Recursive Function

A recursive function is a function that calls itself.

Recursion is a programming technique that allows the programmer to express operations in terms of themselves. In C, this takes the form of a function that calls itself. A useful way to think of recursive functions is to imagine them as a process being performed where one of the instructions is to “repeat the process”. This makes it sound very similar to a loop because it repeats the same code, and in some ways it is similar to looping. On the other hand, recursion makes it easier to express ideas in which the result of the recursive call is necessary to complete the task. Of course, it must be possible for the “process” to sometimes be completed without the recursive call. One simple example is the idea of building a wall that is ten feet high; if I want to build a ten foot high wall, then I will first build a 9 foot high wall, and then add an extra foot of bricks. Conceptually, this is like saying the “build wall” function takes a height and if that height is greater than one, first calls itself to build a lower wall, and then adds one a foot of bricks.

If the function keeps calling itself, how does it know when to stop?

In recursive functions we need to set up a condition, known as a base case. Base cases tell our recursive call when to stop, otherwise it will loop infinitely.

A simple example and a good learning example of recursion would be a factorial.

function factorial($n) {
  if ($n === 0) { // our base case
     return 1;
  else {
     return $n * factorial($n-1); // calling itself.

Leave a Reply

Your email address will not be published. Required fields are marked *