PHP Loops
This video was created by Dani Krossing
Loops are used to carry out repetitive tasks or to repeat a block code until a specific number of times or until conditional has been met. Loops can be an effective way to make your code more efficient, less error-prone, and easier to maintain.
In PHP, there are the following loops:
- while
- do while
- for
- foreach
for
loop, the foreach
loop, and the while
loop.
The type of loop that you use will depend on the task that you are trying to complete. Often you can use more than one kind of loop without any performance difference. However, there is usually a better choice as to which kind of loop you use.
while
The while
loop is the simplest type of loop in PHP. The while
loop, like an if
statement, is made up of a condition and a block of code. Now, while the condition is TRUE
the loop will continue to execute the block of code.
<?php
$count = 1;
// output 1 to 10
while ($count <= 10) {
echo "{$count}, ";
$count++; // increment by 1
}
?>
Now, there are two important parts of the loop. The first is that a loop must have a condition and two, something about that condition has to change during the course of the loop. If it does not, then the result will be an infinite loop.
<?php
$count = 1;
// This will create an infinite loop
// because $count will always be less than 10
while ($count <= 10) {
echo "$count <br>";
}
?>
NOTE
While it will not create an error, an infinite loop will cause your program to get stuck and eventually fail. It is important to avoid infinite loops.
The while
loop typically used when the number of iteration is unknown or random. For example, flipping a coin until you get heads may take only 1 try or it might take 100 tries. The number of tries is unknown.
<?php
$coin = 1;
// keep looping until $coin === 0
while ($coin) {
// randomly choose a number between 0 and 1
$coin = rand(0, 1);
echo "{$coin} <br>";
}
?>
While loops are also often used in conjunction with reading a recordset from a database query or reading the contents of a text file. As long as PHP is able to continue fetching records from the recordset or reading lines from the text file then the loop continues. As soon as the function fails then the loop stops. You can also put a break
command inside the loop, wrapped in an if statement. The break
command will force PHP to exit from the loop.
for
The for
loop is the most complex loop in PHP. The loop consists of three expressions separated by semi-colons and enclosed in parentheses and statements.
The three expressions are as follows:
- The initialization of the iterator
- The condition, which is checked before each loop to see if the loop should continue
- The iteration of the iterator
The statement is enclosed in a set of curly braces ({}
) and is executed each the statement loops as long as the condition evaluates to true.
for (initialization; condition; iteration) {
statement;
}
The structure of the for
loop is similar to the example used when discussing the while
loop. In the following example, a while
loop is used to output 1 to 10.
<?php
$count = 1; // initialization
// output 1 to 10
while ($count <= 10) { // condition
echo "{$count}, ";
$count++; // iteration
}
?>
This same task can be done using the the for
loop
<?php
// output 1 to 10
for ($count = 1; $count <= 10; $count++) {
echo "{$count}, ";
}
?>
The for
loop can be used to iterate over an indexed array. This is accomplished by initializing the variable to serve as the array index, and the condition will be as long as the index is less than the number of items in the array. The count()
function can be used to get the number of items in an array.
<?php
$ages = [4, 8, 15, 16, 23, 42];
$numOfItems = count($ages);
for ($index = 0; $index < $numOfItems; $index++) {
echo "{$ages[$index]} <br>";
}
?>
NOTE
The above example only works with indexed arrays. For associative arrays, use the foreach
loop.
foreach
The foreach
loop is the easiest way to iterate over arrays, especially associative arrays.
The syntax of the foreach
loop is a little different. First, unlike the while
and for
loops, there is no condition in the foreach
loop. The foreach
will simply continue through the array until it reaches the end. There is also no incrementing in the foreach
loop as this is all handled by PHP.
The expression of the foreach
loop is made up of the array, the keyword as
, and the value of each item in the array.
foreach ($array as $value) {
statement;
}
The value of $value
will change each time the foreach
loop loops, as the next item's value is stored in it.
<?php
$ages = [4, 8, 15, 16, 23, 42];
foreach ($ages as $age) {
echo "Age: {$age} <br>";
}
?>
The foreach
loop can also be used with associative arrays. When working with associative arrays, it is helpful to also have each item's label or key. This is done with a slight modification to the foreach
loop's syntax.
foreach ($array as $key => $value) {
statement;
}
Like the $value
, the value of $key
will change each time the foreach
loop loops, and $key
will received the next item's label or key.
NOTE
The variables for holding the keys and values do NOT need to be $key
and $value
. They can be called whatever you want.
<?php
$person = [
"first_name" => "Kevin",
"last_name" => "Skoglund",
"address" => "123 Main Street",
"city" => "Beverly Hills",
"state" => "CA",
"zip_code" => "90210"
];
foreach ($person as $attribute => $data) {
$attr_nice = ucwords(str_replace("_", " ", $attribute));
echo "{$attr_nice}: {$data}<br>";
}
?>