Specifications

Line 1
Line 2
Line 1
Line 2
Line 1
Line 2
Because the code in these examples is properly indented, you can probably see the difference
between them at a glance. The indenting of the code is intended to give readers a visual inter-
pretation of what lines are affected by the for loop. However, note that spaces do not affect
how PHP processes the code.
In some languages, code blocks affect variable scope. This is not the case in PHP.
Recursion
Recursive functions are supported in PHP. A recursive function is one that calls itself. These
functions are particularly useful for navigating dynamic data structures such as linked lists and
trees.
However, few Web-based applications require a data structure of this complexity, and so we
have minimal use for recursion. Recursion can be used instead of iteration in many cases
because both of these allow you to do something repetitively. Recursive functions are slower
and use more memory than iteration, so you should use iteration wherever possible.
In the interest of completeness, we will look at a brief example shown in Listing 5.5.
LISTING 5.5 recursion.phpIt Is Simple to Reverse a String Using Recursion
The Iterative Version Is Also Shown
function reverse_r($str)
{
if (strlen($str)>0)
reverse_r(substr($str, 1));
echo substr($str, 0, 1);
return;
}
function reverse_i($str)
{
for ($i=1; $i<=strlen($str); $i++)
{
echo substr($str, -$i, 1);
}
return;
}
Reusing Code and Writing Functions
C
HAPTER 5
5
REUSING CODE
AND
WRITING
FUNCTIONS
143
07 7842 CH05 3/6/01 3:35 PM Page 143