Loops in PHP
Introduction to Loops
Loops are control structures that allow you to repeat a block of code multiple times. They are fundamental in programming as they help in executing repetitive tasks efficiently. PHP supports several types of loops:
- while loop
- do-while loop
- for loop
- foreach loop
while Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax:
while (condition) {
// code to be executed
}
Example:
$x = 1;
while ($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
The number is: 2
The number is: 3
The number is: 4
The number is: 5
do-while Loop
The do-while loop will always execute the block of code once, and then it will check the condition and repeat the loop while the specified condition is true.
Syntax:
do {
// code to be executed
} while (condition);
Example:
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
The number is: 2
The number is: 3
The number is: 4
The number is: 5
for Loop
The for loop is used when you know in advance how many times the script should run. It consists of three parts: initialization, condition, and increment.
Syntax:
for (initialization; condition; increment) {
// code to be executed
}
Example:
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10
foreach Loop
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
Syntax:
foreach ($array as $value) {
// code to be executed
}
Example:
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
green
blue
yellow