Author: | |
Website: | |
Page title: | |
URL: | |
Published: | |
Last revised: | |
Accessed: |
A loop is a programming construct that enables part of a program to be executed repeatedly, either a predetermined number of times (iterations) or until some exit condition is satisfied. In loops that execute code for a set number of times, an integer counter variable is provided that is incremented by some value on each iteration of the loop. An exit condition is a variable or expression, embodied within the loop, that must evaluate to FALSE before the program can exit the loop.
Loops that repeatedly execute code for a fixed number of times are called counting loops. The counter variable used is set to an initial value (usually zero) and a maximum number of iterations is defined. The amount by which the counter variable is incremented on each iteration of the loop (usually one) is called the step value. Once the maximum number of iterations have occurred, the program exits the loop.
PHP provides two loop control statements that allow us to modify the flow of program execution within a loop. Circumstance can arise in which we want to exit a loop before a counter variable reaches its maximum value, or before an exit condition has been satisfied. PHP provides the break statement to enable us to do just that. There may also be circumstances in which we want to skip over the current iteration of a loop without executing any code. PHP provides the continue statement for that purpose.
Loops are essential for efficient programming. Imagine having to write the same line of code dozens or even hundreds of times in order to process the contents of a large array, or having to search through that many lines of code in order to track down an error. Writing programs would become unbearably tedious.
Loops make the task of processing large arrays or carrying out other repetitive tasks relatively easy, as well as being far less time consuming, and certainly far more efficient, than writing the same code over and over again. They can even be nested inside other loops in order to process more complex data structures such as multi-dimensional arrays.
PHP provides four loop constructs. The list below shows the loop constructs available, and gives a brief description of each.
The for loop is a counting loop because the code within the body of the loop will be executed a set number of times. That number is determined by the maximum value specified for a counter variable, the initial value of which is (usually) set to zero. The syntax of the PHP for loop is as follows:
for (expression1; expression2; expression3) {
// code to be executed on each iteration of the loop
}
Here, expression1 is a statement that sets the initial value of the counter variable and is executed only once. This would typically be something like $i = 0 which initialises the counter variable $i to zero. Note that although the initial value of the counter variable is normally set to zero, it can be set to any integer value (it can even have a negative value).
The maximum value of the counter is determined by expression2. This is the conditional statement that will be evaluated on each iteration of the loop, and must evaluate to TRUE in order for the code in the body of the loop to be executed. If the counter variable has an initial value of zero, and we want the code in the body of the loop to execute ten times, we use a conditional statement such as $i < 10. As soon as the value of $i reaches 10, expression2 evaluates to FALSE and the loop terminates.
The statement represented by expression3 is executed after each iteration of the loop, and increments the value of the counter variable. The amount by which the counter variable is incremented after each iteration is known as the step value. Although the step value is usually one, we can specify larger step values (we'll see an example of that later). The counter variable can even be decremented until it reaches some minimum (as opposed to maximum) value.
If you have read the article "Working with Arrays" in this section, you may remember that we described using a for loop to process an indexed array, so the following script may look quite familiar to you:
<?php
$trees = ["Oak", "Ash", "Beech", "Elm", "Sycamore", "Cedar"];
$count = count($trees);
echo "Trees:<br>";
for($i = 0; $i < $count; $i++) {
$index = $i+1;
echo "<br>$index. $trees[$i]";
}
// Trees:
//
// 1. Oak
// 2. Ash
// 3. Beech
// 4. Elm
// 5. Sycamore
// 6. Cedar
?>
In this example, we have an indexed array called $trees that contains six elements. The value of each element is a string containing the name of a tree. We determine how many times the code in the body of the for loop should be executed using PHP's built-in count() function to get the size of the $trees array and assign that value to the variable $count. The for loop's counter variable ($i) is set to an initial value of zero, and is incremented by one on each iteration of the loop until it equals $count, at which point the loop terminates.
The for loop is only really suitable for use with indexed arrays. For associative arrays or objects, we should use a foreach loop (more about that shortly). We should point out, however, that indexed arrays in PHP are not the same as indexed arrays in other programming languages in that they are not automatically re-indexed when array elements are removed, so there may be gaps in the indexing.
Keep in mind also the PHP sees indices in the same way it sees keys in an associative array. In other words, to PHP, an index is just a key with an integer value. Let's see what happens if we add another element to our $trees array and give it the index number 10:
<?php
$trees = ["Oak", "Ash", "Beech", "Elm", "Sycamore", "Cedar"];
$trees[10] = "Larch";
$count = count($trees);
echo "Trees:<br>";
for($i = 0; $i < $count; $i++) {
$index = $i+1;
echo "<br>$index. $trees[$i]";
}
// Trees:
//
// 1. Oak
// 2. Ash
// 3. Beech
// 4. Elm
// 5. Sycamore
// 6. Cedar
// Warning: Undefined array key 6 . . .
//
// 7.
?>
As we can see, the count() function returns the correct number if items in the $trees array, but the last item in the array is not echoed to the screen. Instead, a warning message is generated because an element with an index of 6 does not exist in the array. Unless we are absolutely certain that an array is indexed consecutively from zero, we should re-index the array using the array_values() function before attempting to process it with a for loop. For example:
<?php
$trees = ["Oak", "Ash", "Beech", "Elm", "Sycamore", "Cedar"];
$trees[10] = "Larch";
//
//
//
$trees = array_values($trees);
$count = count($trees);
echo "Trees:<br>";
for($i = 0; $i < $count; $i++) {
$index = $i+1;
echo "<br>$index. $trees[$i]";
}
// Trees:
//
// 1. Oak
// 2. Ash
// 3. Beech
// 4. Elm
// 5. Sycamore
// 6. Cedar
// 7. Larch
?>
If we have a purely static indexed array, i.e. a zero-indexed array that has a fixed number of elements and no gaps in the indexing and no possibility of having any of its elements removed, then a for loop can safely be used to iterate over the array. For example:
<?php
$chessSymbols = [
"♔ - White King", "♕ - White Queen", "♖ - White Rook",
"♗ - White Bishop", "♘ - White Knight", "♙ - White Pawn",
"♚ - Black King", "♛ - Black Queen", "♜ - Black Rook",
"♝ - Black Bishop", "♞ - Black Knight", "♟ - Black Pawn"
];
$count = count($chessSymbols);
echo "HTML Chess Symbols:<br><br>";
for ($i = 0; $i < $count; $i++) {
echo "$chessSymbols[$i]<br>";
}
// HTML Chess Symbols:
//
// ♔ - White King
// ♕ - White Queen
// ♖ - White Rook
// ♗ - White Bishop
// ♘ - White Knight
// ♙ - White Pawn
// ♚ - Black King
// ♛ - Black Queen
// ♜ - Black Rook
// ♝ - Black Bishop
// ♞ - Black Knight
// ♟ - Black Pawn
?>
Bear in mind, however, that when processing arrays as we have in the examples above, it is almost always the case that we can achieve the same results using a foreach loop. The for loop comes into its own when we are carrying out repeated operations that don't involve array variables or objects. The following script calculates and displays the first 15 numbers in the Fibonacci sequence:
<?php
$a = 0;
$b = 1;
echo "The first 15 Fibonacci numbers:<br><br>";
echo "$a, ";
for($i = 1; $i < 15; $i++) {
$c = $a;
$a = $a + $b;
if ($i < 14) {
echo "$a, ";
}
else {
echo "$a.";
}
$b = $c;
}
// 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377.
?>
There is no totally straightforward algorithm to generate Fibonacci numbers, so we have to output the first number in the sequence (0) outside the for loop. We compensate by setting the loop's counter variable to 1 rather than zero. The first iteration of the loop actually calculates the second number in the sequence, the second iteration calculates the third number, and so on. The loop executes 14 times in total.
The for loop is useful for generating just about any kind of number sequence. Let's suppose, for example, that we want to generate an arithmetic sequence starting from some initial value. An arithmetic sequence is a sequence in which the common difference between consecutive terms is constant. Consider the following example:
<?php
$start = 1;
$inc = 4;
$count = 10;
echo "An arithmetic sequence of 10 numbers<br>";
echo "(start value 1, common difference 4):<br><br>";
for($i = $start; $i < $count*$inc; $i+=$inc) {
if ($i < ($count-1)*$inc) {
echo "$i, ";
}
else {
echo "$i.";
}
}
// An arithmetic sequence of 10 numbers
// (start value 1, common difference 4):
//
// 1, 5, 9, 13, 17, 21, 25, 29, 33, 37.
?>
In this example, we set the $start variable to 1 - the starting value for our arithmetic sequence. We use this variable to initialise the loop counter variable $i. We then assign a step value of 4 to the $inc variable, which is then used to increment the value of $i by 4 after each iteration of the loop. We could have hard-wired these values in the loop itself, but we wanted to make the same code work for different values of $start, $count and $inc.
The foreach loop construct is used to iterate over arrays and objects. Instead of relying on a counter variable to loop through an array, it traverses the array one element at a time, in order, executing the code within the body of the foreach loop for each element or object property it encounters. The syntax of the foreach loop can take one of the following forms:
foreach ($iterable as $value) {
// code to be executed on each iteration of the loop
}
foreach ($iterable as $key=>$value) {
// code to be executed on each iteration of the loop
}
The $iterable variable can be an array variable or an object variable. In the first syntax shown above, the value of the current array element or object property is assigned to $value on each iteration of the loop. In the second syntax shown above, as well as assigning the value of the current array element or object property to $value, the key of the current array element, or the name of the current object property, is assigned to $key on each iteration of the loop.
The foreach loop construct is particularly useful for working with associative arrays in which each element consists of a key-value pair, or with objects in which each of the object's properties also consists of a key-value pair. It also works with indexed arrays because PHP sees the index number of an element in an indexed array as just another key, even though it has an integer value.
We introduced the foreach loop in the article "Working with Arrays" in this section. If you read that article, the following example should be familiar to you:
<?php
$trees = ["Oak", "Ash", "Beech", "Elm", "Sycamore", "Cedar", "Larch", "Maple"];
$index = 0;
echo "Trees:<br>";
foreach($trees as $tree) {
$index += 1;
echo "<br>$index. $tree";
}
// Trees:
//
// 1. Oak
// 2. Ash
// 3. Beech
// 4. Elm
// 5. Sycamore
// 6. Cedar
// 7. Larch
// 8. Maple
?>
No counter variable is needed here. We increment the value of the $index variable on each iteration of the loop so that we can display a numbered list on screen. Each time the loop executes, the value of $index is incremented by one, and the value of the current array element is displayed on a new line as a numbered list item.
After each iteration of a foreach loop, the loop advances automatically to the next element in the array (note that the array's internal pointer remains unchanged). When the last element has been processed, the foreach loop terminates.
In the above example, we were working with an indexed array. We used the first syntactical form of the foreach loop, producing a numbered list by incrementing an external variable ($index) on each iteration of the loop to generate the list numbers. We can also use this form when working with associative arrays (arrays consisting of key-value pairs) if we just want to produce a list of array values. More often, though, we want to display the key of an array element as well as its value. Here is one of the examples we used in the "Working with Arrays" article:
<?php
$alphaGR = [
"Αα"=>"Alpha",
"Ββ"=>"Beta",
"Γγ"=>"Gamma",
"Δδ"=>"Delta2",
"Εε"=>"Epsilon",
"Ζζ"=>"Zeta",
"Ηη"=>"Eta",
"Θθ"=>"Theta",
"Ιι"=>"Iota"
];
echo "<p>Letters of the Greek Alphabet:</p>";
echo "<table>";
echo "<tr><th>Symbol</th><th>Name</th></tr>";
foreach($alphaGR as $symbol=>$name) {
echo "<tr><td>$symbol</td><td>$name</td></tr>";
}
echo "</table>";
?>
In this example, we have used the second syntactical form of the foreach loop construct. We have used the array keys and their associated values to create an HTML table containing character symbols from the Greek alphabet, together with the corresponding character names. The output in a browser window will look something like the following illustration:
A table containg letters of the Greek Alphabet
A foreach loop is frequently used to generate HTML lists and tables dynamically in PHP scripts, often working with array data that has been extracted from a database on the server.
Under normal circumstances, any changes made to an array value during the execution of a foreach loop do not change the value stored in the array itself. For example, let's suppose we want to take the names stored in an array of that contains a company distribution list and display the contents as an HTML list using upper case characters. We could do something like this:
<?php
$distributionList = [
"FJB"=>"Frederick J. Bloggs",
"MM"=>"Molly Malone",
"ES"=>"Ebenezer Scrooge",
"JTK"=>"James Tiberius Kirk",
"WA"=>"William Adama",
"JD"=>"Johnny Dangerously"
];
echo "<p>Senior management distribution list:</p>";
echo "<ul>";
foreach($distributionList as $inits=>$name) {
$name = strtoupper($name);
echo "<li>";
echo "$inits - $name";
}
echo "</ul>";
?>
The output in a browser window will look something like this:
The script generates an HTML list
Let's now suppose that as well as wanting to display the distribution list using upper-case characters, we want to change the distribution list itself to all upper-case characters. We can do this by addressing each value stored in the array by reference in our foreach loop. This is achieved using the PHP address-of operator (&) as shown in this revised version of our distribution list script:
<?php
$distributionList = [
"FJB"=>"Frederick J. Bloggs",
"MM"=>"Molly Malone",
"ES"=>"Ebenezer Scrooge",
"JTK"=>"James Tiberius Kirk",
"WA"=>"William Adama",
"JD"=>"Johnny Dangerously"
];
echo "<p>Senior management distribution list:</p>";
echo "<ul>";
foreach($distributionList as $inits=>&$name) {
$name = strtoupper($name);
echo "<li>";
echo "$inits - $name";
}
unset($name);
echo "</ul>";
var_dump($distributionList);
// array(6) { ["FJB"]=> string(19) "FREDERICK J. BLOGGS" ["MM"]=> string(12) "MOLLY MALONE" ["ES"]=> string(16) "EBENEZER SCROOGE" ["JTK"]=> string(19) "JAMES TIBERIUS KIRK" ["WA"]=> string(13) "WILLIAM ADAMA" ["JD"]=> &string(18) "JOHNNY DANGEROUSLY" }
?>
This script will display the HTML list in exactly the same way as before, but as you can see, the output from the var_dump() function, when applied to the $distributionList array, shows that the string values are now stored in the array as all upper-case strings - and apart from using the unset() function and the var_dump() function, the only other thing we have changed in the script is to insert the address of operator (&) in front of the $name variable in the foreach loop's header.
We have used the unset() function here because the variable $name will remain as a reference to the last element in the array even after the foreach loop has terminated. It is recommended to destroy variables that address array values by reference as soon as they have served their purpose in order to prevent the array value being inadvertently changed by code elsewhere in the script.
The foreach loop can also be used to iterate over the public properties of an object, as demonstrated by the following example:
<?php
class Employee {
public $firstName;
public $lastName;
public $employeeNumber;
public $post;
private $dateOfBirth;
protected $emailAddress;
public function __construct(
$firstName,
$lastName,
$employeeNumber
) {
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->employeeNumber = $employeeNumber;
}
public function addPost($post) {
$this->post = $post;
}
public function addEmail($email) {
$this->emailAddress = $email;
}
public function addDateOfBirth($dob) {
$this->dateOfBirth = $dob;
}
};
$employee_00001 = new Employee("Johnny", "Walker", "00001");
$employee_00001->addPost("Manager");
$employee_00001->addEmail("jwalker@gmail.com");
$employee_00001->addDateOfBirth("1997-06-19");
foreach($employee_00001 as $key=>$value) {
echo "$key: $value<br>";
}
// firstName: Johnny
// lastName: Walker
// employeeNumber: 00001
// post: Manager
?>
In this example, we have created a class called Employee that has a number of member properties and methods. We then declare an object variable $employee_00001 as an instance of Employee, passing the first name, last name and employee number of the new employee to the class constructor. Next, we add the employee's job title, together with their email address and date of birth, using the methods provided.
As you can see from the output from this script, the foreach loop iterates over all of the visible properties in an object, i.e. properties that are declared as public in the class definition. Class members declared as private can only be accessed by the class that defines the class member. Class members declared as protected can be accessed by the class that defines the class member, and by any parent or child classes (we'll be looking at classes and objects in more detail in another article).
Before we move on from the foreach loop construct, you may recall if you have read the article "Working with Arrays" that we discussed destructuring an array using either the list() function or the equivalent shorthand square brackets notation ([]). Basically, this entails extracting the values stored in an array and assigning them to separate variables that are easier to work with.
When used together with a foreach loop, the list() function or its shorthand equivalent can be used to simplify the task of coding when dealing with multi-dimensional arrays. We will demonstrate how this works using the square brackets notation, which directly unpacks array elements into variables within the header of the foreach loop, avoiding the overhead of a function call and slightly reducing the amount of code we need to write. Consider the following example:
<?php
$students = [
["name"=>"Anderson, N", "score"=>51],
["name"=>"Beckham, D", "score"=>31],
["name"=>"Einstein, A", "score"=>99],
["name"=>"Foster, R", "score"=>95],
["name"=>"Miller, G", "score"=>75]
];
echo "Student Results:<br>";
foreach($students as ["name"=>$name, "score"=>$score]) {
echo "<br>$name: $score";
}
// Student Results:
//
// Anderson, N: 51
// Beckham, D: 31
// Einstein, A: 99
// Foster, R: 95
// Miller, G: 75
?>
The $students array is an indexed array in which each element is an associative array containing the name of a student and their test score. We iterate through the $students array using a foreach loop, within which the elements within each subarray are unpacked into separate variables ($name and $score). This is a relatively straightforward example, but one that hopefully demonstrates just how easily we can deal with complex data structures using the [] language construct in combination with a foreach loop.
As with PHP's conditional statements, which we described in the article "Conditional Statements" in this section, there is an alternative syntax for the foreach loop in which the opening curly brace is replaced by a colon (:), and the closing curly brace is replaced by endforeach. Here is a revised version of the script above that demonstrates the alternative notation:
<?php
$students = [
["name"=>"Anderson, N", "score"=>51],
["name"=>"Beckham, D", "score"=>31],
["name"=>"Einstein, A", "score"=>99],
["name"=>"Foster, R", "score"=>95],
["name"=>"Miller, G", "score"=>75]
];
echo "Student Results:<br>";
foreach($students as ["name"=>$name, "score"=>$score]):
echo "<br>$name: $score";
endforeach;
?>
The while loop, as its name suggests, executes the code within the body of the loop while some conditional expression evaluates to TRUE. The syntax of the while loop is as follows:
while ( conditional expression ) {
// code to be executed on each iteration of the loop
}
We used the following example in the article "Working with Arrays" to demonstrate how a while loop might be used to iterate through the values stored in an indexed array of prime numbers:
<?php
$primes = [2,3,5,7,11,13,17,19];
$currentVal = reset($primes);
while ($currentVal !== FALSE) {
echo "The current value is: $currentVal<br>";
$currentVal = next($primes);
};
// The current value is: 2
// The current value is: 3
// The current value is: 5
// The current value is: 7
// The current value is: 11
// The current value is: 13
// The current value is: 17
// The current value is: 19
?>
The conditional expression $currentVal !== FALSE must evaluate to FALSE before the while loop will be terminated. Before entering the while loop, we use the reset() function to set the array pointer to the start of the array, and set the value of $currentVal equal to that of the first element in the array.
On each iteration of the loop, the value of $currentVal is set to whatever value is stored in the location pointed to by the array pointer. The array pointer is then advanced to the next element in the array using the next() function, which returns that element's value. The exit condition is that $currentVal must have the Boolean value FALSE. This happens when the next() function fails to find any more array elements and returns FALSE, satisfying the exit condition. The while loop then terminates.
The while loop does not run a specific number of times like the for loop. Nor does it necessarily have to iterate over every element of an array like the foreach loop. It will only continue to run while the conditional expression defined in the head of the while loop evaluates to TRUE. For that reason, it is important to ensure that the exit condition (that the conditional expression evaluates to FALSE) will eventually be satisfied.
Note that the while loop evaluates the conditional expression at the top of the loop, i.e. before the code within the body of the loop is executed. This means that if the conditional expression evaluates to FALSE on the first iteration of the loop, the while loop will terminate immediately, and the code in the body of the loop will never be executed. Use a while loop if you want to evaluate the conditional expression before the code in the body of the loop runs.
As with PHP's conditional statements, which we described in the article "Conditional Statements" in this section, there is an alternative syntax for the while loop in which the opening curly brace is replaced by a colon (:), and the closing curly brace is replaced by endwhile. Here is a revised version of the script above that demonstrates the alternative notation:
<?php
$primes = [2,3,5,7,11,13,17,19];
$currentVal = reset($primes);
while ($currentVal !== FALSE):
echo "The current value is: $currentVal<br>";
$currentVal = next($primes);
endwhile;
?>
The do...while loop construct is similar to the while loop in that the code in the body of the loop will run on each iteration of the loop while some conditional expression evaluates to TRUE. The syntax of the do...while loop is as follows:
do {
// code to be executed on each iteration of the loop
} while ( conditional expression )
The main difference here is that, whereas the conditional expression in a while loop is evaluated before the code in the body of the loop is executed, the conditional expression in the do...while loop is evaluated after the code is executed. This means that even if the conditional expression evaluates to FALSE on the first iteration of the loop, the code will still be executed once before the loop terminates.
To demonstrate the do...while loop, we will use the example we used to demonstrate the shuffle() function in the article "Working with Arrays" in this section, slightly reworked. In the original version, we use a while loop to deal four Bridge hands from an array containing fifty-two elements representing the cards in a pack of cards. The array is sorted into a random order using the shuffle() function. This time, we're going to use a do...while loop instead. Here is the script:
<?php
$pack = [
"♠A","♠2","♠3","♠4","♠5","♠6","♠7","♠8","♠9","♠X","♠J","♠Q","♠K",
"♥A","♥2","♥3","♥4","♥5","♥6","♥7","♥8","♥9","♥X","♥J","♥Q","♥K",
"♦A","♦2","♦3","♦4","♦5","♦6","♦7","♦8","♦9","♦X","♦J","♦Q","♦K",
"♣A","♣2","♣3","♣4","♣5","♣6","♣7","♣8","♣9","♣X","♣J","♣Q","♣K"
];
shuffle($pack);
$players = [[],[],[],[]];
echo "Bridge Hands:<br><br>";
$i = 0;
do {
for($j = 0; $j < 4; $j++) {
$card = $pack[$i];
array_push($players[$j], $card);
$i++;
}
} while($i < 52);
for($i = 0; $i < 4; $i++) {
sort($players[$i]);
echo "Player " . ($i +1) . ": ";
for($j = 0; $j < 13; $j++) {
echo $players[$i][$j];
if($j < 12) {
echo ", ";
}
}
echo "<br><br>";
}
// Bridge Hands:
//
//
// Player 1: ♠4, ♠5, ♠7, ♠K, ♠X, ♣6, ♣9, ♣J, ♥8, ♥J, ♥X, ♦1, ♦J
//
// Player 2: ♠1, ♠6, ♠A, ♠Q, ♣2, ♣4, ♣Q, ♥5, ♦5, ♦6, ♦7, ♦K, ♦X
//
// Player 3: ♠3, ♠8, ♠J, ♣3, ♣8, ♣X, ♥2, ♥6, ♥7, ♦2, ♦3, ♦9, ♦Q
//
// Player 4: ♠2, ♣5, ♣7, ♣A, ♥3, ♥4, ♥9, ♥A, ♥K, ♥Q, ♦4, ♦8, ♦A
?>
As you can see, as well as the $pack array variable, we have a two-dimensional array called $players containing four elements, each of which is the empty array. Each of these four arrays will be assigned one element from $pack in turn, until all of the elements in $pack have been assigned, and the four sub-arrays in $players have each been assigned thirteen elements from $pack. This is the code that "deals the hands", so to speak:
$i = 0;
do {
for($j = 0; $j < 4; $j++) {
$card = $pack[$i];
array_push($players[$j], $card);
$i++;
}
} while($i < 52);
As you can see, we use a for loop inside the do...while loop to deal each of the four "players" thirteen cards from the randomly sorted "pack". The loop executes until the counter variable $i, which is incremented on each iteration of the inner for loop, reaches a value of 52, at which point the do...while loop's exit condition is satisfied and the loop terminates.
The break statement enables us to break out of a loop even in the loop's conditional statement still evaluates to TRUE (in the case of a while or do...while loop) or the counter variable has not reached its maximum value (in the case of a for loop) or the loop has not processed all of the elements in an array or the properties in an object (in the case of a foreach loop).
Use a break statement to terminate loop execution if a condition arises that satisfies the purpose of the loop prematurely, i.e. before the loop's exit condition is satisfied. This might be the case, for example, when using a loop to search for a specific value in an array. The following examples demonstrate how a break statement might be used in a for loop:
<?php
$trees = ["Oak", "Ash", "Beech", "Elm", "Sycamore", "Cedar"];
$count = count($trees);
$searchTerm = "Elm";
$result = "Search term \"$searchTerm\" not found.";
for($i = 0; $i < $count; $i++) {
$currentVal = $trees[$i];
if($currentVal == $searchTerm) {
$result = "Search term \"$searchTerm\" found at index $i.";
break;
}
}
echo $result;
// Search term "Elm" found at index 3.
?>
We could do something similar with a foreach loop:
<?php
$alphaGR = [
"Αα"=>"Alpha",
"Ββ"=>"Beta",
"Γγ"=>"Gamma",
"Δδ"=>"Delta2",
"Εε"=>"Epsilon",
"Ζζ"=>"Zeta",
"Ηη"=>"Eta",
"Θθ"=>"Theta",
"Ιι"=>"Iota"
];
$searchTerm = "Zeta";
$result = "Search term \"$searchTerm\" not found.";
foreach($alphaGR as $symbol=>$name) {
if($name == $searchTerm) {
$result = "Search term \"$searchTerm\" found.<br>";
$result .= "Upper and lower-case symbols: $symbol.";
break;
}
}
echo $result;
// Search term "Zeta" found.
// Upper and lower-case symbols: Ζζ.
?>
The break statement ends a loop immediately, after which program execution continues with the program statement that follows the loop. If the break statement is omitted from either of the above examples, the end result will be the same, but the loop will continue to iterate needlessly even after the search term is found.
Sometimes we want to iterate through a loop until the exit condition is satisfied, but skip over the current iteration if we determine there is no need to complete that iteration. If this is indeed the case, we can halt execution of the current iteration and skip to the next using the continue statement. Consider the following example:
<?php
function isPrime($num) {
if ($num <= 1) {
return FALSE;
}
for ($i = 2; $i < $num; $i++) {
if ($num % $i == 0) {
return FALSE;
}
}
return TRUE;
}
$primes = [];
$num = 50;
for($i = 0; $i <= $num; $i++) {
if(!isPrime($i)) {
continue;
}
$primes[] = $i;
}
$strPrimes = implode(", ", $primes);
echo "Prime numbers between 0 and $num:<br><br>";
echo $strPrimes;
// The prime numbers between 0 and 50:
//
// 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47
?>
Here, we declare a function called isPrime() that takes an integer value as its argument and tests whether it is a prime number or not. We then declare an integer variable $num to hold some maximum value, and an empty array variable $primes. A for loop is used to iterate through the numbers from 0 to $num and apply the isPrime() function to each. If a number is found to be prime, it is added to the $primes array. Otherwise, a continue statement terminates the current iteration of the loop and the next iteration is started.
In this example we don't want to add a number to our $primes array unless it really is a prime number, so once we have determined that the number being evaluated by the current iteration is not a prime number, we invoke the continue statement to skip over the part of the loop that adds the number to $primes and carry on to the next iteration.
Loops are said to be nested when one loop - of any kind - sits inside another. The inner loop runs through its complete range of iterations for each iteration of the outer loop, unless a break statement or a continue statement interrupts the flow of either loop. For two nested for loops, for example, if the outer for loop iterates six times and the inner for loop iterates ten times, then the inner for loop will potentially iterate a total of sixty times.
If you have read the article "Working with Arrays" in this section, you may recall that we touched on the use of nested loops for processing multi-dimensional arrays. We reproduce below the example we used to demonstrate how we might use nested foreach loops to process a two-dimensional array holding a matrix:
<?php
$matrix = [
[25, 24, 31],
[47, 58, 86],
[17, 78, 99]
];
foreach ($matrix as $row) {
foreach ($row as $col) {
echo $col . " ";
}
echo "<br>";
}
// 25 24 31
// 47 58 86
// 17 78 99
?>
Nested loops can be used to process multi-dimensional arrays that hold data extracted from a relational database. In the "Working with Arrays" article mentioned above, we saw an example of a four-dimensional array that holds details of customer orders. We laboriously accessed each array element with a separate statement in order to output the details of each order to the screen. In this kind of situation, we can achieve the same result far more efficiently using a nested loop construct. The script below does just that:
<?php
$orders = [
["orderNum"=>"0123", "cust"=>"Smith & Co", "items"=>
[
["id"=>"1234A", "desc"=>"Widget", "qty"=>6],
["id"=>"5678B", "desc"=>"Sprocket", "qty"=>12],
["id"=>"1066C", "desc"=>"Rocker", "qty"=>3]
]
],
["orderNum"=>"0456", "cust"=>"ACME Inc", "items"=>
[
["id"=>"9876D", "desc"=>"Thingy", "qty"=>5],
["id"=>"5432E", "desc"=>"Gadget", "qty"=>5],
["id"=>"1002F", "desc"=>"Doofer", "qty"=>10]
]
]
];
echo "<strong>Orders on hand:</strong><br><br>";
for($i = 0; $i < count($orders); $i++) {
echo "<p>Order number: " . $orders[$i]['orderNum'] . "<br>";
echo "Customer: " . $orders[$i]['cust'] . "</p>";
echo "<table>";
echo "<tr><th>Qty</th><th>Item ID</th><th>Description</th></tr>";
foreach($orders[$i]['items'] as $item) {
echo "<tr><td>" . $item['qty'] . "</td>";
echo "<td>" . $item['id'] . "</td>";
echo "<td>" . $item['desc'] . "</td></tr>";
}
echo "</table><br>******************";
}
?>
This is what the script's output looks like in a browser window:
The script ´creates a table containing details of customer orders
In this example we use a for loop to cycle through the orders, outputting the order number and customer name for each order. Nested within the for loop we have a foreach loop, which cycles through the order items, outputting the quantity, item ID and description for each order item as an HTML table row (the table's column headers are set up before the inner foreach loop runs).