Share this content:
Now that we have seen some basic functionalities of PHP we are going to introduce the loops. In this article we will show how to execute code repeatedly until some condition has been met with some useful examples, and in particular we are going to learn how to use PHP loops. If you really like this series of articles, please share and help us to grow.
Other articles of the same series
The PHP loops
PHP supports 4 main loop constructs:
Let’s see what each one is doing
The for loop
The for loops in PHP behaves like the C ones. Their syntax is:
for (initial-condition; ending-condition; increment) {
..do something..;
}
What this does is
- first expression initial-condition is evaluated/executed once unconditionally at the beginning of the loop
- ending-condition is evaluated at the beginning of each iteration and if it is evaluated false then the loops ends.
- At the end of each iteration increment is evaluated/executed
See the example below
<?php
// sum the numbers until 10
$counter = 0;
for($i = 0; $i <= 10; $i++){
$counter = $counter + $i;
}
echo $counter;
?>
You can enrich the loop printing more information if you want
<?php
// sum the numbers until 10
$counter = 0;
for($i = 0; $i <= 10; $i++){
$counter = $counter + $i;
echo "Iteration $i, Total: $counter\n";
}
echo $counter;
?>
As it is there is no much use we can do, but let’s assume we want instead to sum all the numbers stored into an array
<?php
// sum all the numbers in $array
$array = [2,3,4,5,7,8,90,19,23];
$counter = 0;
for($i = 0; $i < sizeof($array); $i++){
$counter = $counter + $array[$i];
echo "Iteration $i, array item: {$array[$i]}, Total: $counter\n";
}
echo $counter;
?>
And this is the output
Iteration 0, array item: 2, Total: 2
Iteration 1, array item: 3, Total: 5
Iteration 2, array item: 4, Total: 9
Iteration 3, array item: 5, Total: 14
Iteration 4, array item: 7, Total: 21
Iteration 5, array item: 8, Total: 29
Iteration 6, array item: 90, Total: 119
Iteration 7, array item: 19, Total: 138
Iteration 8, array item: 23, Total: 161
if you want you can also sum the first half the array or the second half of the array
<?php
// sum all the first half and second half numbers of $array
$array = [2,3,4,5,7,8,90,19,23];
$len = round(sizeof($array)/2);
echo $len;
$firstHalf = 0;
for($i = 0; $i < $len; $i++){
$firstHalf = $firstHalf + $array[$i];
echo "Iteration $i, array item: {$array[$i]}, Total: $firstHalf\n";
}
echo "First half total: $firstHalf\n";
$secondHalf = 0;
for($i = $len; $i < sizeof($array); $i++){
$secondHalf = $secondHalf + $array[$i];
echo "Iteration $i, array item: {$array[$i]}, Total: $secondHalf\n";
}
echo "Second half total: $secondHalf\n"
?>
Or, because the ending-condition is evaluated at each iteration, we can decide to stop the loop iteration until the total sum is below 100 and see how many of the items produced that number.
<?php
// sum all the numbers in $array until the sum is < 100 version 1
$array = [2,3,4,5,7,8,90,19,23];
$counter = 0;
for($i = 0; $i < sizeof($array) && $counter<100 ; $i++){
$counter = $counter + $array[$i];
echo "Iteration $i, array item: {$array[$i]}, Total: $counter\n";
}
echo "First $i items produced $counter\n";
?>
// output
Iteration 0, array item: 2, Total: 2
Iteration 1, array item: 3, Total: 5
Iteration 2, array item: 4, Total: 9
Iteration 3, array item: 5, Total: 14
Iteration 4, array item: 7, Total: 21
Iteration 5, array item: 8, Total: 29
Iteration 6, array item: 90, Total: 119
First 7 items produced 119
As you can see from the output of the example above, the result is not exactly what we wanted. This is because between 29 and 90 the total counter was still smaller than 100, went into the next iteration and added 90, producing 119. What we really want is the example below:
<?php
// sum all the numbers in $array until they are < 100
$array = [2,3,4,5,7,8,90,19,23];
$counter = 0;
for($i = 0; $i < sizeof($array) && ($counter + $array[$i]) <= 100 ; $i++){
$counter = $counter + $array[$i];
echo "Iteration $i, array item: {$array[$i]}, Total: $counter\n";
}
echo "First $i items produced $counter\n";
?>
In the evaluating-expression we are checking 2 things:
- the index is still within the array boundaries ($i < sizeof($array))
- the number we are summing will keep the counter smaller or equals to 100 ($counter + $array[$i]) <= 100 ; $i++)
As you can see tings can start to be really complicated if we want to, we will review this example later and show how we can interrupt the loop when a particular condition is meet during the loop execution itself. One of the alternative to the for loop (which syntax we have seen is not immediate to remember) is the while
The while loop
The while loop executes a block of code until a specified condition is evaluated true, the syntax is like below
while (ending-condition is true) {
..do something..;
}
If we want to translate the first example we did with the for into a while, one approach could be like this
<?php
// sum all the numbers up to 10
$counter = 0;
$index = 0;
while($index < 10){
$counter = $counter + $i;
$index++;
//or $index = $index+1;
//or $index += 1;
}
echo $counter;
?>
As you can see from the example above the syntax seems to be easier, however we have moved out the initial condition $index = 0 is outside the while loop and the increment is within the while block {…}. The behaviour is the same and we achieve the same result, the only difference is that we could have $index = 11 before the while and this code was never executed. In short this will be handy if in some circumstances where the ending-condition could be a result of some other operations executed before the while. Let’s now translate the last example we had with the for loop into a while block. We looped through an array and added up all the numbers until the total sum was below 100
<?php
// sum all the $array numbers until they are < 100
$array = [2,3,4,5,7,8,90,19,23];
$i = 0;
$counter = 0;
while ($i < sizeof($array) && ($counter + $array[$i]) <= 100) {
$counter = $counter + $array[$i];
echo "Iteration $i, array item: {$array[$i]}, Total: $counter\n";
$i++;
}
echo "First $i items produced $counter\n";
?>
//output
Iteration 0, array item: 2, Total: 2
Iteration 1, array item: 3, Total: 5
Iteration 2, array item: 4, Total: 9
Iteration 3, array item: 5, Total: 14
Iteration 4, array item: 7, Total: 21
Iteration 5, array item: 8, Total: 29
First 6 items produced 29
As you can see we reused a lot of the previous code and we just moved the increment inside the while block and the initial condition outside. However if you change $counter to be 100, this code will never be executed. If you want the code to be executed at least once you must use the do..while
The do..while
The do while is a construct that allow the code to be executed at least once because the ending condition is evaluated after the code iteration and not before like for the for and while. The syntax is
do {
..do something..;
} while( ending-condition is true);
In our case, our first example of adding up the numbers up to 10, will be something like
<?php
// sum up all the numbers from 0 up to 10
$i = 0;
$counter = 0;
do {
$counter = $counter + $i;
$i++;
} while ($i < 10);
echo $counter;
?>
At the first look could seems to be identical however we must be very careful when using this construct because that code is guaranteed to be executed at least once, and this could end up in having unexpected results. Let’s have a look at the latest example (add up numbers from an array until 100) and convert into a do..while
<?php
// sum all the $array numbers until they are < 100
$array = [2,3,4,5,7,8,90,19,23];
$i = 0;
$counter = 0;
do {
$counter = $counter + $array[$i];
echo "Iteration $i, array item: {$array[$i]}, Total: $counter\n";
$i++;
} while ($i < sizeof($array) && ($counter + $array[$i]) <= 100);
echo "First $i items produced $counter\n";
?>
As you can see the output is what we expected! However if we change the code slightly like below
<?php
// sum all the $array numbers until they are < 100
$array = [2,3,4,5,7,8,90,19,23];
$i = 0;
$counter = 100;
do {
$counter = $counter + $array[$i];
echo "Iteration $i, array item: {$array[$i]}, Total: $counter\n";
$i++;
} while ($i < sizeof($array) && ($counter + $array[$i]) <= 100);
echo "First $i items produced $counter\n";
?>
//output
Iteration 0, array item: 2, Total: 102
First 1 items produced 102
The result is not what we expected! And this is due to the fact that with the do..while, the code that is in this block is guaranteed to be executed at least once because the ending condition is evaluated after the code iteration. It is important to remember this distinction because can end up in unexpected results.
The Foreach
The foreach construct is an easy way to loop through arrays, it works only on arrays and objects and it has two syntaxes
//syntax 1
foreach (iterable-element as $value) {
.. do something ..;
}
//syntax 2
foreach (iterable-element as $key => $value) {
.. do something ..;
}
Let’s have a closer look by looking at some examples, in the example below we are showing the first type of syntax for the foreach:
<?php
// foreach example syntax 1
$array = [2,3,4,5,7,8,90,19,23];
echo "Syntax 1\n";
foreach($array as $item) {
echo "$item \n";
}
?>
Syntax 1
2
3
4
5
7
8
90
19
23
Nothing unexpected, we perform a loop over an array and we are printing the elements that belong to it.
Let’s have a look at the second syntax
<?php
// foreach example syntax 2
echo "Syntax 2\n";
foreach($array as $key => $item){
echo "key = $key => value = $item\n";
}
?>
Syntax 2
key = 0 => value = 2
key = 1 => value = 3
key = 2 => value = 4
key = 3 => value = 5
key = 4 => value = 7
key = 5 => value = 8
key = 6 => value = 90
key = 7 => value = 19
key = 8 => value = 23
With the $key => $item in the foreach syntax we are expanding the array cells and getting 2 values for each: the key of the array cell and the value of that cell. The foreach with numeric arrays it does not express the full potential. Let’s have a look at this other example
<?php
$users = [
"John" => ["age" => 18, "class" => 4, "role" => "student"],
"Ed" => ["age" => 18, "class" => 4, "role" => "student"],
"Sean" => ["age" => 19, "class" => 4, "role" => "student"],
"Mark" => ["age" => 19, "class" => 4, "role" => "student"],
"Lucy" => ["age" => 20, "class" => 4, "role" => "student"],
"Stacy" => ["age" => 55, "class" => 4, "role" => "teacher"],
];
foreach($users as $name => $values){
echo "$name is a {$values["role"]}";
echo " in class {$values["class"]}"
echo " and is {$values["age"]}\n";
}
?>
And here is the output
John is a student in class 4 and is 18
Ed is a student in class 4 and is 18
Sean is a student in class 4 and is 19
Mark is a student in class 4 and is 19
Lucy is a student in class 4 and is 20
Stacy is a teacher in class 4 and is 55
The foreach can be really powerful when dealing with records coming from database or for manipulating and accessing really complex data structures.
In summary we have explored the 4 types of loops that PHP has to offer, there is no one better than the other, however there is the most suitable for each occasion. In our next article we will explore more about loops and introduce the break and continue.
Please share and help us to grow!