PHP Recursive Functions

In this chapter you will learn:

  1. What is a recursive function
  2. How to write recursive functions
  3. Example - A PHP recursive function

Description

A recursive function is a function which call itself.

How

Here's a quick overview of how a recursive function operates:

The recursive function is called by the calling code If the base case is met, the function does required calculation, then exits.

Otherwise, the function does required calculation, then calls itself to continue the recursion.

Example

Here is an example to calculate factorials:


<?PHP/*  j a  v  a2 s  . c  o  m*/
function factorial($number) { 
        if ($number == 0) return 1; 
        return $number * factorial($number-1); 
} 

print factorial(6); 
?>

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. What is PHP Anonymous Functions
  2. Why do we need Anonymous Functions
  3. Syntax to create anonymous functions
  4. Example - creates an anonymous function dynamically based on the value of a variable
Home » PHP Tutorial » PHP Function Create
PHP Function
PHP Function Create
PHP Function Parameter
PHP Function Default Parameters
PHP Variable Length Parameter
PHP Function Reference Parameter
PHP Function Return
PHP Return Reference
PHP Variable Scope in Functions
PHP Global Variables
PHP Recursive Functions
PHP Anonymous Function
PHP static variable