jump to navigation

Iteration and Recursion in PHP October 9, 2010

Posted by Tournas Dimitrios in PHP.
trackback

Repeated operations are handled either by recursion or loops (iteration). One of the fundamental structures of programming is loops .Lets first introduce the consept of looping (iteration) .

Loops are an important tool that help in automating repetitive tasks within a program. PHP supports four different types of loops :

  • The while Loop
  • The do-while Loop
  • The for Loop
  • The foreach Loop vs iterating over arrays

The while Loop :

The easiest type of loop to understand is the while loop, which repeats continuously while a prespecified condition is true. Here’s an example, which uses a loop to repeatedly print an ‘x’ to the output page.

.
< ? p h p
// repeat continuously until counter becomes 10
// output: 'xxxxxxxxx'
$counter = 1;
while ($counter < 10) {    echo 'x';    $counter++; 
 }  
?>
.

Notice the condition enclosed in parentheses; so long as this condition evaluates to true, the code within the curly braces is executed. As soon as the condition becomes false, the loop stops repeating, and the lines following the loop are executed in the usual fashion.

The do-while Loop :

With a while loop, the condition to be evaluated is tested at the beginning of each loop iteration. There’s also a variant of this loop, the do-while loop, which evaluates the condition at the end of each loop iteration. Here’s a revision of the preceding example that
illustrates it in action:

.
< ? p h p
// repeat continuously until counter becomes 10
// output: 'xxxxxxxxx'
$counter = 1;
do {
  echo 'x';
  $counter++;
} while ($counter < 10);  
?>
.

The difference in structure should also be apparent: with a do-while loop, the condition to be evaluated now appears at the bottom of the loop block, rather than the beginning.The difference in behavior between a while loop and a do-while loop has one  important implication: with a while loop, if the conditional expression evaluates to false on the first pass itself, the loop will never be executed. With a do-while loop, on the other hand, the loop will always be executed once, even if the conditional expression is false, because the condition is evaluated at the end of the loop iteration rather than the beginning.

The for Loop :

The while and do-while loops are fairly simple: they repeat for so long as the specified condition remains true. But PHP also supports a more sophisticated type of loop, the for loop, which is useful when you need to execute a set of statements a specific number of times.
The best way to understand a for loop is by looking at some code. Here’s a simple example, which lists the numbers between 1 and 10:

.
< ? p h p
// repeat continuously until counter becomes 10
// output:
for ($x=1; $x<10; $x++) {  
  echo "$x ";  
}  ?>
.

In this listing, the loop begins by initializing the counter variable $x to 1; it then executes the statements that make up the loop. Once it reaches the end of the first loop iteration, it updates the loop counter by adding 1 to it, checks the conditional expression to
ensure that the counter hasn’t yet reached 10, and executes the loop once more. This process continues until the counter reaches 10 and the conditional expression becomes false.As this listing illustrates, there are thus three expressions involved in the typical for
loop, separated by semicolons and enclosed in parentheses:
●  The first of these is an assignment expression, which initializes the loop counter to a
specific value—in this case, assigning the value 1 to the variable $x.
●  The second is a conditional expression, which must evaluate to either true or false;
the loop will continue to execute so long as this condition remains true. Once the
condition becomes false, the loop will stop executing.
●  The third is again an assignment expression, which is executed at the end of each loop
iteration, and which updates the loop counter with a new value—in this case, adding 1
to the value of $x.

Interrupting and Skipping Loops :

While on the topic of loops, it’s interesting to discuss two PHP statements that allow you to either interrupt a loop or skip a particular iteration of a loop. PHP’s break statement is aptly named: it allows you to break out of a loop at any point. To illustrate, consider the following loop, which would normally iterate five times but stops after the second iteration due to the break  statement:

.
< ?  ph p
$count = 0;
// loop 5 times
while ($count <= 4) { 
    $count++;    
 // when the counter hits 3    
 // break out of the loop    
 if ($count == 3) {   
      break;    
 }    
 echo "This is iteration #$count "; 
}
 ?>
.

Unlike break, continue doesn’t halt processing of the loop; it simply “jumps one” iteration. To see how this works, consider the following loop, which iterates five times but skips the third iteration due to the intervention of the continue statement:

.
< ? p h p
$count = 0;
// loop 5 times
while ($count <= 4) {     $count++;    
 // when the counter hits 3  
 // skip to the next iteration   
 if ($count == 3) {  
       continue;   
  }    
 echo "This is iteration #$count ";
 } 
?>
.

The foreach Loop :

With a foreach loop, each time the loop runs, the current array element is assigned to a temporary variable, which can then be processed in any way you please—printed, copied to another variable, used in a calculation, and so on. Unlike a for loop, a foreach loop doesn’t use a counter; it automatically “knows” where it is in the array, and it moves forward continuously until it reaches the end of the array, at which point it automatically halts.The best way to understand this marvel of automation is with an example. The next listing shows it in action, rewriting the preceding listing to use a foreach loop instead of a for loop

.
< ? p h p  
 // define array 
  $cities = array('London', 'Paris', 'Madrid', 'Los Angeles', 'Bombay', 'Jakarta'); 
// iterate over array   
// print each value   
foreach ($cities as $c) { 
    echo "$c \r\n";  
 }  
 ?>
.

The foreach loop also works with associative arrays, except that for such arrays, it uses two temporary variables (one each for the key and value). The next listing illustrates the difference:


.
< ? p h p 
  // define array  
 $cities = array(    "United Kingdom" => "London",
  "United States" => "Washington",
  "France" => "Paris",
  "India" => "Delhi"
);

// iterate over array
// print each value
foreach ($cities as $key => $value) {
  echo "$value is in $key. \r\n";
}
?>

.

Iterating the array with OOP approach : The array Iterator

.
< ? p h p 
  // define array  
 $cities = array(    "United Kingdom" => "London",
  "United States" => "Washington",
  "France" => "Paris",
  "India" => "Delhi"
);

// create an ArrayIterator object
$iterator = new ArrayIterator($cities);

// rewind to beginning of array
$iterator->rewind();

// iterate over array
// print each value
while($iterator->valid()) {
    print $iterator->current() . " is in " . $iterator->key() . ". \r\n";
    $iterator->next();
}
?>
.

In this listing, an ArrayIterator object is initialized with an array variable, and the object’s rewind() method is used to reset the internal array pointer to the first element of the array. A while loop, which runs so long as a valid() element exists, can then be used to iterate over the array. Individual array keys are retrieved with the key() method, and their corresponding values are retrieved with the current() method. The next() method moves the internal array pointer forward to the next array element.

In general terms, iteration is a pretty straightforward concept, which as you saw, can be applied in different programming cases with minor hassles. However, let me go one step further in my explanation: say you’ve defined a PHP function that need to be called repetitively within an application, in order to traverse dynamic data structures such as trees or linked lists. In this case, you’re likely to use what is commonly called a “recursive function.”

Essentially, a recursive function can be defined as a regular function that calls itself. Sounds like a confusing concept? It isn’t. Fortunately, PHP supports the definition of recursive functions, which can be useful in certain situations. For instance, you’ll want to use a recursive function if you’re going to do a lot of work with data trees, which are structured as database tables, or in cases where template files contain nested placeholders and need to be recursively parsed, or making factorial equations ( in statistical analysis ) or displaying the directory structure of a filesystem , and so on. You get the idea.

A typical example is calculation of the factorial.

.
< ? p h p
 function factorial($n) { 
    if ($n==0) {   
      return 1; 
    } else { 
        return $n * factorial($n - 1); 
    } }
 echo factorial(4), "\n"; 
echo factorial(10), "\n";
 ?>

In this code example, we calculate the factorial of two numbers.

 return $n * factorial($n - 1);

Inside the body of the factorial function, we call the factorial function with a modified argument. The function calls itself.

$ php recursion.php
24
3628800

These are the results.

Read further on recursion in PHP here >>>>

The same consept also applays to actionscript read my article here >>>>

Ref:124…

Advertisements

Comments»

No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s