This is a quick and easy tutorial that will teach you how to create and use recursive functions properly. But... what is a recursive function? Well put simply, a recursive function is a function that calls itself an undetermined amount of times... like a loop.
Hmm... so it calls itself non-stop... wont that create a memory leak? Well, the point of recursive functions are that they have an escape clause in them. If they didnt, they would keep running to infinity... only stopping when the process is killed or when memory runs out. Not good.
But used properly, recursive functions can be very useful.
So How Should I Use One?
As this is a simple tutorial, I will not go indepth with an over-the-top example on their uses. To keep things simple, a simple scenario has been constructed.
You have a multidimentional array that contains only numbers. It looks like this:
- Code: Select all
Array (
1,
5,
10,
Array (
4,
100,
Array (
1337
)
)
)
Now you could use array_sum() to calculate the sum of that array... but that would return 16. That is because it only counts the numbers in the root array and not the arrays contained within.
Heres where recursion comes in.
Time For The Code
As I have mentioned before, this is a quick tutorial, therefore I won't go into the code line by line. Instead i'll leave it up to the comments to explain themselves.
- Code: Select all
// The function takes one parameter which is an array
function array_sum_recursive($array) {
// Define a total variable with the value of 0
$total = 0;
// Loop through the array given in the parameters
foreach ($array as $key) {
// If the key is numeric, i.e. a number, add it to the total variable
if (is_numeric($key)) {
$total += $key;
}
// If the key is an array...
if (is_array($key)) {
// Lets do some recursion
// This runs the same function but passes the key as the parameter
// This is because the key is an array
// Once the key is run through this function, the returned total
// Is added to this total variable
$total += array_sum_recursive($key);
}
}
// Return the total variable with the sum of keys in the passed array
return $total;
}
Thats a very simple example of a recursive function. There are ways to improve it but its not that important. It works and thats what matters.
Virtualise This Function!
This "trace" is using the multidimensional array that was shown in the So How Should I Use One? section.
- Code: Select all
$total = array_sum_recursive($array);
-----
1 + 5 + 10 = 16
|
-- 4 + 100 = 104
|
-- 1337 = 1337
-----
16 + 104 + 1337 = 1457
-----
$total = 1457
Its that easy.
Useful Links
Google - Search for recursion... notice the spelling correction?
Wikipedia - A complete article about recursion... not for the faint hearted.
Conclusion
Well I hope that this tutorial has shown you the basics of creating a recursive function. Remember that recursion doesnt only apply to PHP. Any language that supports procedures or functions supports recursion [citation needed].
Ozzy
