Specifications

In this listing, we have implemented two functions. Both of these will print a string in reverse.
The function reverse_r() is recursive, and the function reverse_i() is iterative.
The reverse_r() function takes a string as parameter. When you call it, it will proceed to call
itself, each time passing the second to last characters of the string. For example, if you call
reverse_r(“Hello”);
it will call itself a number of times, with the following parameters:
reverse_r(“ello”);
reverse_r(“llo”);
reverse_r(“lo”);
reverse_r(“o”);
reverse_r(“”);
Each call the function makes to itself makes a new copy of the function code in the servers
memory, but with a different parameter. It is like pretending that we are actually calling a dif-
ferent function each time. This stops the instances of the function from getting confused.
With each call, the length of the string passed in is tested. When we reach the end of the string
(strlen()==0), the condition fails. The most recent instance of the function (reverse_r(“”))
will then go on and perform the next line of code, which is to echo the first character of the
string it was passedin this case, there is no character because the string is empty.
Next, this instance of the function returns control to the instance that called it, namely
reverse_r(“o”). This prints the first character in its string”o”and returns control to the
instance that called it.
The process continuesprinting a character and then returning to the instance of the function
above it in the calling orderuntil control is returned back to the main program.
There is something very elegant and mathematical about recursive solutions. In most cases,
however, you are better off using an iterative solution. The code for this is also in Listing 5.5.
Note that it is no longer (although this is not always the case with iterative functions) and does
exactly the same thing.
The main difference is that the recursive function will make copies of itself in memory and
incurs the overhead of multiple function calls.
You might choose to use a recursive solution when the code is much shorter and more elegant
than the iterative version, but it will not happen often in this application domain.
Although recursion appears more elegant, programmers often forget to supply a termination
condition for the recursion. This means that the function will recur until the server runs out of
memory, or until the maximum execution time is exceeded, whichever comes first.
Using PHP
P
ART I
144
07 7842 CH05 3/6/01 3:35 PM Page 144