Introduction
At the heard of the matter loops are a mechanism for executing instructions (code) multiple times.
Loops give us the ability to automate certain tasks that can be done in a number or repeatable steps.
Types of Loops
In PHP we have various types of loops and although at the core of it all they do the same thing, they go about doing it differently. Its important to note that certain things can be done with less effort in some loop structures while it may not be the case for other loop structures.
Notes on Loop Syntax
Loop syntax varies slightly for all loops, but the important thing to keep in mind is that the loops conduct a check before every iteration and expect a Boolean value during this check. This Boolean value tells the PHP interpreter whether it should continue to the rest of the code or continue executing the current block of code contained by the loop structure.
Loop structures have a block of code that is executed when the Boolean value is set to true. The block of code is defined between curly brackets ( { and } ), but if the curly brakets are omitted, then only the line following the loop declaration will be considered part of the loop’s block.
”while” and “do“.. “while” Loops
The while loop is the simplest in terms of syntax and has the widest range of uses. Declaring a while loop is as simple as using the keyword, while, followed by a boolean value or boolean expression wrapped in parenthesis followed by a block of code in curly brackets.
|
1 2 3 4 5 6 7 |
<?php
$x = 0;
while($x < 10) {
echo $x, "<br>\n";
$x++;
} |
Take note that the expression: $x < 10 , is a evaluated to a true or false, and the code between the curly brackets is executed only when this expression is true. Be aware that we can substitute any boolean expression in this place.
Warning: Setting forth an infinite(∞) loop is a possibility when the expression never evaluates to false, in which case the script would run the code in the loop until either the server kills the script or the server runs out of resources. This can be a problem in a shared hosting environment, where a web host may suspend your hosting for excessive use of resources.
The do…while loop is a variation of the while loop. The do…while loop guarantees that the block of code in the loop will be executed at least once. To use this type of loop, you use the keyword, do, followed by the block of code in curly brackets and the keyword while with a Boolean value or expression in parenthesis.
|
1 2 3 4 5 6 7 |
<?php
$x = 0;
do{
echo $x;
$x++;
} while ($x < 0); |
Its important to note in this example the comparison is between a variable and a value of zero, the expression at the end will evaluate to false and the loop will stop there. However the code block was executed once because the comparison did not take place until after the block of code. This is a property unique to the do…while loop.
Note: The semi-colon after the while(..) is required, otherwise the code will yield errors.
Parts of a “for” loop
A for loop is a bit more complex than its while counter part, it contains a variable initialization, check condition, and a step.
This loop can be said to be a loop that keeps track of its own progress. A typical for loop is declared by using the keyword, for, followed by the three mentioned items wrapped in parenthesis and the block of code that will be executed.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php
$genres = array('Blues', 'Country', 'Rock', 'Rap');
/*
* Start our index at 0
*
* Execute the block as long as the number is
* less than the number of items in the array
*
* After executing the code, add one to the count (index).
*/
for($index = 0; $index < count($genres); $index++) {
// Access the n-th element of he $genres array.
// n-th refers to the number held by $index.
echo 'Do you like ', $genres[$index] ," music?<br>\n";
}
/*
* Simple example 2, counting from 1 to 10
*/
for($num = 1; $num <= 10; $num++){
echo $num, ',';
} |
As you can see from our example, the variable $num is declared and set to a value of one when we declare our for loop. The second part of the parameter listing is the boolean check that dictates the number of iterations our loop will go through. The last parameter is the step that our loop is to take after executing the block of code, in this case our step adds one to the value of $num.
It should also be noted that the variable $num will be available outside the block of the for loop, it’s continues to exist after the loop.
The “foreach“ loop
The foreach loop is a special type of loop that is best used with iterateable items like arrays and objects. A foreach loop takes uses the keyword foreach and as in the following manner.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php
$colors = array('red', 'blue', 'green', 'magenta','cyan','yellow');
/*
* Each value fo the $colors array will be referred to as
* a $color (singular) inside the array.
*/
foreach($colors as $color){
echo 'Do you like the color ', $color ,"?<br>\n";
} |
Note that each of the items in our array ($list) was referred to as $a_value inside the block of code.
The number of time the loop would execute is dependent on how many items are in the provided parameter.
If you have an associative array (or an object) you can also use the following syntax to retrieve the name of the key (or property) and the value.
example_foreach_key_value.php:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php
$alphabet = array( 'first' => 'a',
'second' => 'b',
'third' => 'c');
foreach($alphabet as $spot => $letter) {
/* Each key and value combo will be referred to as
* $spot for the key name
* $letter for the value of each key and value combination
*/
echo 'The ', $spot ,' letter is ', $letter, ".<br>\n";
} |
Take note how the => operator was used to indicate the name of the variable we used to reference the key and the name of the variable we used to reference the value of the current element.
The foreach loop is commonly used to deal with arrays when each value in the array needs to be processed.
Comparison
Below we have an example of how the we can print the contents of an array to the screen using all the types of loops covered above.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
<?php echo '<pre>'; $br = "\n"; // Line Break $list = array( 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ); /* * USING WHILE LOOP */ echo $br, "+WHILE OUTPUT------------------------------+", $br; $count = 0; // Array index begins at 0 while ($count < count($list)) { echo $list[$count] , $br; $count++; // Move index to next one by adding 1 } /* * USING A DO WHILE LOOP */ echo $br, "+DO...WHILE OUTPUT------------------------------+", $br; $count = 0; // Reset our count do { echo $list[$count] , $br; $count++; // Move index to next one by adding 1 } while ($count < count($list)); /* * USE A FOR LOOP */ echo $br, "+FOR OUTPUT------------------------------+", $br; for ($count = 0; $count < count($list); $count++) { echo $list[$count] , $br; } /* * USE A FOREACH LOOP */ echo $br, "+FOREACH OUTPUT------------------------------+", $br; foreach ($list as $day) { echo $day, $br; } echo $br, "print_r OUTPUT------------------------------+", $br; print_r($list); echo '</pre>'; |
Breaking out
Loops check whether a condition has changed after every iteration, sometimes its necessary to exit a loop when a condition outside this primary condition is reached. The break keyword is used inside a loop to indicate that the loop should be exited.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?php $br = "<br>\n"; // Numbers from 0 to 4 displayed $count = 0; while ($count < 5) { echo $count, $br; $count++; } // Numbers 0 displayed $count = 0; while ($count < 5) { echo $count, $br; $count++; // Exit our loop break; } // Numbers from 0 to 3 $count = 0; while ($count < 5) { echo $count, $br; $count++; // Exit our loop when count reaches a value of 4 if($count == 4) break; } |
In the example above we have a break statement inside our while loop that simply exits the loop as soon as the PHP parser reaches the line. We also have the break after an if-condition that allows us to specify when we should exit the loop.
Using the break keyword is simple, and it is typically used to exit loops in special cases specified by you with series of conditionals inside the loop. The example demonstrated this ability with the while loop, but it works in the same manner with the other types of loops.
Summary
In summary the loop structures in PHP are, while, do…while, for, and foreach. These loops have varying syntax’s and required parameters. At the root they all execute a block of code a number of times dictated by a given condition. Note that they can be used interchangeably for the most part, but certain tasks are made easier by some loop structures.