Thursday, January 22, 2009

Creating loops

As the name suggests, a loop is a section of code that is repeated over and over again until a certain condition is met. Loops are often controlled by setting a variable to count the number of iterations. By increasing the variable by one each time, the loop comes to a halt when the variable gets to a preset number. The other way loops are controlled is by running through each item of an array. When there are no more items to process, the loop stops. Loops frequently contain conditional statements, so although they’re very simple in structure,they can be used to create code that processes data in often sophisticated ways.


Loops using while and do... while
The simplest type of loop is called a while loop. Its basic structure looks like this:
while (condition is true) {
do something
}
The following code displays every number from 1 through 100 in a browser (you can test it in while.php in the download files for this chapter). It begins by setting a variable ($i)
to 1, and then using the variable as a counter to control the loop, as well as display the
current number onscreen.
$i = 1; // set counter
while ($i <= 100) {
echo "$i "; $i++; // increase counter by

1 } A variation of the while loop uses the keyword do and follows this basic pattern:
do { code to be executed }
while (condition to be tested);

The only difference between a do... while loop and a while loop is that the code within the do block is executed at least once, even if the condition is never true.

The following code (in dowhile.php) displays the value of $i once, even though it’s greater than the maximum expected.

$i = 1000;
do {
echo "$i ";
$i++; // increase counter by 1
} while ($i <= 100);

The danger with while and do... while loops is forgetting to set a condition that brings the loop to an end, or setting an impossible condition. When this happens, you create an infinite loop that either freezes your computer or causes the browser to crash.

The versatile for loop

The for loop is less prone to generating an infinite loop because you are required to declare all the conditions of the loop in the first line.
The for loop uses the following basic pattern:

for (initialize counter; test; increment)
{ code to be executed }

The following code does exactly the same as the previous while loop, displaying every number from 1 to 100 (see forloop.php):

for ($i = 1; $i <= 100; $i++)
{ echo "$i "; }

The three expressions inside the parentheses control the action of the loop (note that they are separated by semicolons, not commas):

The first expression shows the starting point. You can use any variable you like, but the convention is to use $i. When more than one counter is needed, $j and $k are frequently used.

The second expression is a test that determines whether the loop should continue to run. This can be a fixed number, a variable, or an expression that calculates a value.

The third expression shows the method of stepping through the loop. Most of the time, you will want to go through a loop one step at a time, so using the increment (++) or decrement (--) operator is convenient.

There is nothing stopping you from using bigger steps. For instance, replacing $i++ with $i+=10 in the previous example would display 1, 11, 21, 31, and so on.

Looping through arrays with foreach


The final type of loop in PHP is used exclusively with arrays. It takes two forms, both of which use temporary variables to handle each array element. If you only need to do something with the value of each array element, the foreach loop takes the following form:

foreach (array_name as temporary_variable) {
do something with temporary_variable
}
The following example loops through the $shoppingList array
and displays the name of each item, as shown in the screenshot
(see shopping_list.php):
$shoppingList = array('wine', 'fish', ➥
'bread', 'grapes', 'cheese');
foreach ($shoppingList as $item) {
echo $item.'
';
}
Although the preceding example uses an indexed array, you can also use it with an associative array. However, the alternative form of the foreach loop is of more use with associative arrays, because it gives access to both the key and value of each array element. It takes this slightly different form:

foreach (array_name as key_variable => value_variable) {
do something with key_variable and value_variable
}


This next example uses the $book associative array from the “Creating arrays” section earlier and incorporates the key and value of each element into a simple string, as shown in the screenshot (see book.php):

foreach ($book as $key => $value) {
echo "The value of $key is $value
";
}


Breaking out of a loop

To bring a loop prematurely to an end when a certain condition is met, insert the break keyword inside a conditional statement. As soon as the script encounters break, it exits the loop. To skip an iteration of the loop when a certain condition is met, use the continue keyword. Instead of exiting, it returns to the top of the loop and executes the next iteration.

0 comments:

Post a Comment