PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

PHP Recursive Function Example: Factorial Numbers

Note: This article was originally published at Planet PHP on 29 May 2012.
Planet PHP

I spun up the simplest example I could think of to illustrate a recursive function to a PHP beginner the other day, and I thought I'd share. I often don't post really basic content but I should - people are beginning to be beginners all the time, after all!

Factorials

Factorials are a very easy maths concept. They are written like 5! and this means 5 * 4 * 3 * 2 * 1. So 6! is 720 and 4! is 24.

6! is the same as 6 * 5!, or 6 * 5 * 4! ... and this is where the recursive functions come in.

Recursive Functions

We're going to do the same thing, over and over, using the output of the previous function call to inform what to pass into the next function call - so we need a recursive function! Here's my code snippet for calculating factorials:

function factorial($number) { A if ($number 2) { return 1; } else { return ($number * factorial($number-1)); } }

You can call factorial(6) for example, and it will first of all figure out that it should jump into the else clause. However this causes a call to factorial so PHP will go to work that out and realise that it needs to call the function again ... and so on. When ($number - 1) eventually gets small enough, we'll return a 1 rather than calling the function again, and each of the nested function calls will find its return value and return. When we get to the top of the call stack, we've got the answer!

I personally really like recursive functions for operations like this, calculating the fibonacci series is also a nice example, and I also use an approach like this for processing potentially-nested data in arrays for example. So if the value of the next element is an array, pass the whole thing into a recursive call to this function, otherwise do whatever you were going to do ... sometimes the simplest solutions are the best!

Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist. This post was originally published at LornaJane