Today I am going to give an example of recursion in PHP. There are some cases where recursion will be a more elegant solution to a given problem than iteration will be.
If you don't already know what recursion is, the simplest way I can explain it is recursion is a function that calls itself.
To give you a better idea of how you can use recursion, here is a very simple example.
Let's say you want to be able to call a function that will count down from whatever number you send as an argument to zero ... but you don't want to use a loop. Instead you could do the following:
//recursive count down function function count_down($number) { // check to make sure we have been sent a number if (is_numeric($number)) { return false; } // echo pause between numbers echo ' ... '; // if $number is less then 1, we end our count down if ($number < 1) { // echo final output echo 0; } else { // if we can still continue our count down we echo the number to the // screen and call count_down again, as you can see this could also be // done in a loop, but for our purpose we are using a recursive function echo $number; count_down($number-1); } return true; } // call to our count down function and see if it was successful if (count_down(10)) { echo ' ... Lift Off!'; } else { echo 'You are doing it wrong!'; }This function would output the following:
... 10 ... 9 ... 8 ... 7 ... 6 ... 5 ... 4 ... 3 ... 2 ... 1 ... 0 ... Lift Off!
Obviously this is a very basic example and further study is recommended, but I hope that I have made the concept a little bit easier to grasp.
No comments:
Post a Comment