Книга: Fedora™ Unleashed, 2008 edition

Loops

Loops

PHP has four ways you can execute a block of code multiple times: while, for, foreach, and do...while. Of the four, only do...while sees little use; the others are popular and you will certainly encounter them in other people's scripts.

The most basic loop is the while loop, which executes a block of code for as long as a given condition is true. So you can write an infinite loop — a block of code that continues forever — with this PHP:

<?php
 $i = 10;
 while ($i >= 10) {
  $i += 1;
  echo $i;
 }
?>

The loop block checks whether $i is greater or equal to 10 and, if that condition is true, adds 1 to $i and prints it. Then it goes back to the loop condition again. Because $i starts at 10 and only numbers are added to it, that loop continues forever. With two small changes, you can make the loop count down from 10 to 0:

<?php $i = 10;
 while ($i >= 0) {
  $i -= 1;
  echo $i;
 }
?>

So, this time you check whether $i is greater than or equal to 0 and subtract 1 from it with each loop iteration. while loops are typically used when you are unsure of how many times the code needs to loop because while keeps looping until an external factor stops it.

With a for loop, you specify precise limits on its operation by giving it a declaration, a condition, and an action. That is, you specify one or more variables that should be set when the loop first runs (the declaration), you set the circumstances that will cause the loop to terminate (the condition), and you tell PHP what it should change with each loop iteration (the action). That last part is what really sets a for loop apart from a while loop: You usually tell PHP to change the condition variable with each iteration.

You can rewrite the script that counts down from 10 to 0 using a for loop:

<?php
 for($i = 10; $i >= 0; $i -= 1) {
  echo $i;
 }
?>

This time you do not need to specify the initial value for $i outside the loop, and neither do you need to change $i inside the loop — it is all part of the for statement. The actual amount of code is really the same, but for this purpose the for loop is arguably tidier and therefore easier to read. With the while loop, the $i variable was declared outside the loop and so was not explicitly attached to the loop.

The third loop type is foreach, which is specifically for arrays and objects, although it is rarely used for anything other than arrays. A foreach loop iterates through each element in an array (or each variable in an object), optionally providing both the key name and the value.

In its simplest form, a foreach loop looks like this:

<?php
 foreach($myarr as $value) {
  echo $value;
 }
?>

This loops through the $myarr array created earlier, placing each value in the $value variable. You can modify that to get the keys as well as the values from the array, like this:

<?php
 foreach($myarr as $key => $value) {
  echo "$key is set to $valuen";
 }
?>

As you can guess, this time the array keys go in $key and the array values go in $value. One important characteristic of the foreach loop is that it goes from the start of the array to the end and then stops — and by start we mean the first item to be added rather than the lowest index number. This script shows this behavior:

<?php
 $array = array(6 => "Hello", 4 => "World",
                2 => "Wom", 0 => "Bat");
 foreach($array as $key => $value) {
  echo "$key is set to $valuen";
 }
?>

If you try this script, you will see that foreach prints the array in the original order of 6, 4, 2, 0 rather than the numerical order of 0, 2, 4, 6.

If you ever want to exit a loop before it has finished, you can use the same break statement you saw earlier to exit a switch/case block. This becomes more interesting if you find yourself with nested loops — loops inside of loops. This is a common situation to be in. For example, you might want to loop through all the rows in a table and, for each row in that table, loop through each column. Calling break exits only one loop or switch/case, but you can use break 2 to exit two loops or switch/cases, or break 3 to exit three, and so on.

Оглавление книги


Генерация: 0.998. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз