Loops
It's a common requirement to repeat a set of actions. One example would be to output a list of items. PHP supports loops, which is a feature to repeat a set of actions. Loops allow you to execute the same code multiple times without having to write it out over and over again. You can repeat these actions a fixed number of times or until a condition has been met.
This lesson will focus on the for
, while
, do while
, and foreach
loops.
for loop
The for
loop in PHP is a control structure that allows you to repeat a block of code a fixed number of times. It is commonly used when you need to execute a specific block of code a certain number of times, and you know exactly how many times you want to repeat the code.
For loop structure
Here is an example of how the for loop is written in PHP. Let's break down each part of the for
loop:
initialization
: This section of thefor
loop is where you initialize a counter variable, which is used to keep track of the number of times the code has been executed. This section is executed only once, at the beginning of the loop.condition
: This section of thefor
loop specifies the condition that must be met in order for the code inside the loop to be executed. The condition is evaluated before each iteration of the loop. If the condition istrue
, the code inside the loop will be executed. If the condition isfalse
, the loop will terminate.increment
: This section of thefor
loop is used to increment the counter variable. This section is executed after each iteration of the loop, and it allows you to control how many times the code inside the loop will be executed.
for (initialization; condition; increment) {
// code to be executed
}
Using the for loop
Here's an example of how to use the for
loop in PHP:
In this example, we initialize the counter variable $i
to 0
. The condition $i < 10
is checked before each iteration of the loop. As long as $i
is less than 10
, the code inside the loop will be executed. After each iteration, $i
is incremented by 1
using the $i++
statement.
What is the ++ operator?
The ++
operator is called the increment operator. This operator increments a number by one. So, $i++
is the equivalent of $i = $i + 1;
or $i += 1;
.
for ($i = 0; $i < 10; $i++) {
echo "{$i} <br>";
}
Output
This for loop will output the following:
And that's it! The for
loop is a powerful tool in PHP that can be used to repeat a block of code a specific number of times.
0
1
2
3
4
5
6
7
8
9
Alternative for loop syntax
PHP offers an alternative syntax for the for
loop. Instead of using curly brackets, you can use the for
and endfor
keywords.
Here's the same example with these keywords.
for ($i = 0; $i < 10; $i++) :
echo "{$i} <br>";
endfor;
while loop
The while
loop in PHP is a control structure that allows you to repeat a block of code as long as a specified condition is met. The while
loop is commonly used when you want to repeat a block of code an unknown number of times, and you only want the loop to terminate when a certain condition is met.
While loop structure
Here is an example of how the while
loop is written in PHP. Let's break down the while loop:
condition
: This section of thewhile
loop specifies the condition that must be met in order for the code inside the loop to be executed. The condition is evaluated before each iteration of the loop. If the condition istrue
, the code inside the loop will be executed. If the condition isfalse
, the loop will terminate.
while (condition) {
// code to be executed
}
Using the while loop
Here's an example of how to use the while loop in PHP:
In this example, we initialize the counter variable $i
to 0
. The condition $i < 10
is checked before each iteration of the loop. As long as $i
is less than 10
, the code inside the loop will be executed. After each iteration, $i
is incremented by 1
using the $i++
statement.
$i = 0;
while ($i < 10) {
echo "{$i} <br>";
$i++;
}
Output
This while loop will output the following:
And that's it! The while loop is a powerful tool in PHP that can be used to repeat a block of code as long as a specified condition is met. It is important to be careful when using while
loops, as it is possible to create an infinite loop if the condition never becomes false.
0
1
2
3
4
5
6
7
8
9
Alternative syntax
Instead of using curly brackets, we can use the while
and endwhile
keywords to create a while loop. Here's an example:
$i = 0;
while ($i < 10) :
echo "{$i} <br>";
$i++;
endwhile;
do while loop
The do while
loop in PHP is similar to the while
loop, with the only difference being that the code inside the loop will always be executed at least once, even if the condition is not met.
Here is an example of how the do while
loop is written in PHP. Let's break down the do while
loop:
condition
: This section of thedo while
loop specifies the condition that must be met in order for the code inside the loop to be executed again. The condition is evaluated after each iteration of the loop. If the condition istrue
, the code inside the loop will be executed again. If the condition isfalse
, the loop will terminate.
do {
// code to be executed
} while (condition);
Here's an example of how to use the do while
loop in PHP:
In this example, the code inside the loop will be executed at least once, even if $i
is equal to or greater than 10
. After each iteration, the condition $i < 10
is evaluated. As long as $i
is less than 10
, the code inside the loop will be executed. After each iteration, $i
is incremented by 1
using the $i++
statement.
$i = 0;
do {
echo "{$i} <br>";
$i++;
} while ($i < 10);
Output
This do while
loop will output the following:
And that's it! The do while
loop is a powerful tool in PHP that can be used to repeat a block of code as long as a specified condition is met, and it ensures that the code inside the loop will always be executed at least once.
0
1
2
3
4
5
6
7
8
9
while vs do while
Here are the main differences between the while
and do while
loops in PHP:
- Execution order: The
while
loop checks the condition before executing the code inside the loop, whereas thedo while
loop executes the code inside the loop first and then checks the condition. - Guaranteed execution: The code inside the
do while
loop is guaranteed to be executed at least once, even if the condition is not met, whereas, in thewhile
loop, the code may not be executed if the condition is not met.
foreach loop
The foreach
loop in PHP is a convenient way to iterate over elements in an array or elements of an object without explicitly defining and managing loop counters. It simplifies the process of iterating over collections, such as arrays and performing operations on each element.
foreach loop structure
Here's the basic syntax for a foreach
loop in PHP:
Let's break down the foreach
loop:
$array
: This is the array or object that you want to iterate over. It can be an indexed array, an associative array, or an object implementing theTraversable
interface.$element
: This is a temporary variable that represents each element in the array or object as the loop iterates. You can choose any valid variable name for this.
foreach ($array as $element) {
// code to be executed for each $element
}
Using the foreach loop
Within the loop, you can access and work with the current element using the $element
variable. Here's an example that demonstrates how to use the foreach
loop in PHP:
In this example, we have an array called $fruits
containing three elements. The foreach
loop iterates over each element in the $fruits
array and assigns it to the variable $fruit
. Within the loop, we echo each $fruit
followed by a line break.
Naming convention
It's common practice for variables storing an array to use the plural form of a word. In a loop, the variable name for each element will use the singular form.
$fruits = ['apple', 'banana', 'orange'];
foreach ($fruits as $fruit) {
echo $fruit . '<br>';
}
Output
The output of this code will be:
The foreach
loop automatically iterates over every element in the array, without the need to manage loop counters or worry about reaching the end of the array.
apple
banana
orange
Working with associative arrays
Additionally, the foreach
loop can also provide access to both the key and value of each element in an associative array. Here's an example:
In this case, the foreach
loop assigns the array keys to the variable $name
and the array values to the variable $age
. Within the loop, we can use both variables to access the key-value pairs of the associative array.
$ages = ['John' => 25, 'Sarah' => 32, 'Michael' => 19];
foreach ($ages as $name => $age) {
echo "$name is $age years old. <br>";
}
Output
You can expect the output to be the following:
John is 25 years old.
Sarah is 32 years old.
Michael is 19 years old.
Alternative syntax
PHP offers an alternative syntax for the foreach
loop. Instead of using curly brackets, you can use the foreach
and endforeach
keywords.
Here's the same example with these keywords.
$ages = ['John' => 25, 'Sarah' => 32, 'Michael' => 19];
foreach ($ages as $name => $age) :
echo "$name is $age years old. <br>";
endforeach;
break keyword
The break
keyword in PHP is used to break out of a loop early before the condition for the loop has been met. This is useful when you want to stop a loop early, either because you have found what you're looking for or because you want to avoid an infinite loop.
Here's an example of how to use the break
keyword in a for
loop in PHP:
for ($i = 0; $i < 10; $i++) {
if ($i == 5) {
break;
}
echo "{$i} <br>";
}
In this example, the for
loop will run from 0
to 9
. However, when $i
reaches 5
, the break
keyword will be executed, and the loop will terminate. The output of this code will be:
0
1
2
3
4
You can also use the break
keyword in a while
or do while
loop in the same way.
$i = 0;
while ($i < 10) {
if ($i == 5) {
break;
}
echo "{$i} <br>";
$i++;
}
In this example, the while
loop will run until $i
is equal to 10
. However, when $i
reaches 5
, the break
keyword will be executed, and the loop will terminate. The output of this code will be:
0
1
2
3
4
It's important to use the break
keyword sparingly and only when necessary, as it can make your code harder to understand and debug. However, in the right circumstances, it can be a useful tool for controlling the flow of your loop.
continue keyword
The continue
keyword in PHP is used to skip the current iteration of a loop and move on to the next iteration. This is useful when you want to skip certain iterations based on certain conditions.
Here's an example of how to use the continue
keyword in a for
loop in PHP:
for ($i = 0; $i < 10; $i++) {
if ($i % 2 == 0) {
continue;
}
echo "{$i} <br>";
}
In this example, the for
loop will run from 0
to 9
. However, for each iteration, the code inside the loop will check if $i
is an even number by using the modulo operator %
. If $i
is an even number, the continue
keyword will be executed, and the current iteration will be skipped. The output of this code will be:
1
3
5
7
9
You can also use the continue
keyword in a while
or do while
loop in the same way.
$i = 0;
while ($i < 10) {
if ($i % 2 == 0) {
$i++;
continue;
}
echo "{$i} <br>";
$i++;
}
In this example, the while
loop will run until $i
is equal to 10
. However, for each iteration, the code inside the loop will check if $i
is an even number. If $i
is an even number, the continue
keyword will be executed, and the current iteration will be skipped. The output of this code will be:
1
3
5
7
9
In the right circumstances, the continue
keyword can be a useful tool for controlling the flow of your loop and skipping certain iterations.
Breaking or Skipping nested loops
In some cases, you may find yourself writing nested loops. The break
or continue
keywords can be used inside a nested loop. However, it'll only affect the current loop, not all loops. After each keyword, you can add a number to specify the number of loops to affect.
For example:
continue 2
: This means it will skip the current iteration of the immediate loop as well as the next higher loop. So if there are nested loops (a loop inside a loop),continue 2
will skip to the next iteration of both the inner and the outer loop.break 2
: This will terminate the current loop and the next higher loop. If you're in a nested loop,break 2
will exit not just the current loop but also the loop that contains the current loop.
Let's look at an example to better illustrate these concepts:
for ($i = 0; $i < 5; $i++) {
echo "Outer loop iteration: $i \n";
for ($j = 0; $j < 5; $j++) {
if ($j == 2) {
continue 2; // it will skip the rest of both inner and outer loop when $j equals 2
}
echo " Inner loop iteration: $j \n";
}
}
When $j
is 2
, the continue 2
statement is executed, which skips the rest of the current inner loop iteration and also the current outer loop iteration, and moves on to the next iteration of the outer loop.
Exercises
Exercise #1
Rewrite the code changing the for
loop to while
without altering its behavior (the output should stay the same).
for ($i = 0; $i < 3; $i++) {
echo "{$i} <br>";
}
Exercise #2
What is the last value echoed by this code? Why?
$i = 3;
while ($i) {
echo $i--;
}
Exercise #3
Use the for loop
to output even numbers from 2
to 10
.
Exercise #4
This one's going to be tricky. This exercise will have you output prime numbers. An integer number greater than 1
is called a prime if it cannot be divided without a remainder by anything except 1
and itself.
In other words, $n > 1
is a prime if it can't be evenly divided by anything except 1
and $n
.
For example, 5
is a prime because it cannot be divided without a remainder by 2
, 3
, and 4
.
Write the code which outputs prime numbers in the interval from 2
to $n
.
For $n = 10
, the result will be 2,3,5,7
.
P.S. The code should work for any $n
, and not be hard-tuned for any fixed value.
Key takeaways
for
loop: Afor
loop is used to repeat a block of code a specified number of times. It consists of three parts: the initialization, the condition, and the increment/decrement.while
loop: Awhile
loop is used to repeat a block of code as long as a specified condition istrue
.do while
loop: Ado while
loop is similar to awhile
loop, but it will always execute the code inside the loop at least once.foreach
loop: Aforeach
loop is used to repeat a block of code based on the items in an array.break
keyword: Thebreak
keyword is used to break out of a loop early before the specified condition is met.continue
keyword: Thecontinue
keyword is used to skip the current iteration of a loop and move on to the next iteration.- A number can be added after the
break
orcontinue
keywords to affect outer loops outside of the current loop.