Loops are used to repeat the execution of a block of code based on a specified condition. They automate repetitive tasks in a program, saving time and effort. PHP supports four types of loops:
At the end of this chapter, you will learn how to iterate through array values using the foreach()
loop, which is specifically designed for arrays.
The while
statement loops through a block of code as long as the specified condition evaluates to true.
For example, the following code initializes $i=1
. The loop continues to execute as long as $i
is less than or equal to 3. Each iteration increments $i
by 1:
<?php
$i = 1;
while($i <= 3){
$i++;
echo "The number is " . $i . "<br>";
}
?>
The do-while
loop is a variant of the while
loop. It executes the block of code once before checking the condition at the end of each iteration. If the condition is true, the loop continues to execute.
For example, the following code initializes $i=1
. It executes the code block, increments $i
by 1, and prints the output. Then, it evaluates the condition to determine if the loop should continue running as long as $i
is less than or equal to 3:
<?php
$i = 1;
do{
$i++;
echo "The number is " . $i . "<br>";
}
while($i <= 3);
?>
The while
loop and do-while
loop differ in an important way — in a while
loop, the condition is checked at the beginning of each iteration. If the condition is false initially, the loop won't execute at all.
On the other hand, a do-while
loop executes its block of code at least once before checking the condition at the end of each iteration. Even if the condition is false initially, the loop runs once.
The for
loop repeats a block of code based on a specified condition. It's commonly used when you know in advance how many times you want to execute the block of code.
The parameters of a for
loop are interpreted as follows:
initialization
— Initializes the loop counter and is executed once before the loop starts.condition
— Checked before each iteration. If true, the loop continues; if false, the loop ends.increment
— Updates the loop counter after each iteration.For example, the following code initializes $i=1
. The loop continues to execute as long as $i
is less than or equal to 3. Each iteration increments $i
by 1:
<?php
for($i=1; $i<=3; $i++){
echo "The number is " . $i . "<br>";
}
?>
The foreach
loop is specifically designed for iterating over arrays in PHP.
For example, the following code demonstrates how to iterate through and print the values of a given array:
<?php
$colors = array("Red", "Green", "Blue");
// Loop through colors array
foreach($colors as $value){
echo $value . "<br>";
}
?>
There is another syntax variation of the foreach
loop, which extends the basic usage.
<?php
$superhero = array(
"name" => "Peter Parker",
"email" => "peterparker@mail.com",
"age" => 18
);
// Loop through superhero array
foreach($superhero as $key => $value){
echo $key . " : " . $value . "<br>";
}
?>