PHP Loops
PHP loops are used to execute a block of code repeatedly based on a condition. PHP supports four types of loops:
- while loop
- do...while loop
- for loop
- foreach loop
Here's an explanation of each loop type with examples:
1. while Loop
The while
loop executes a block of code as long as the specified condition is true.
$i = 1;
while ($i <= 5) {
echo "The value is $i <br>";
$i++;
}
Output:
The value is 1
The value is 2
The value is 3
The value is 4
The value is 5
2. do...while Loop
The do...while
loop is similar to the while
loop, except the condition is checked at the end of each iteration. This means the block of code will be executed at least once.
$i = 1;
do {
echo "The value is $i <br>";
$i++;
} while ($i <= 5);
Output:
The value is 1
The value is 2
The value is 3
The value is 4
The value is 5
3. for Loop
The for
loop is used when the number of iterations is known. It consists of three parts: initialization, condition, and increment/decrement.
for ($i = 1; $i <= 5; $i++) {
echo "The value is $i <br>";
}
Output:
The value is 1
The value is 2
The value is 3
The value is 4
The value is 5
4. foreach Loop
The foreach
loop is used to iterate over arrays. It works only on arrays and is used to loop through each key/value pair.
$array = array(1, 2, 3, 4, 5);
foreach ($array as $value) {
echo "The value is $value <br>";
}
Output:
The value is 1
The value is 2
The value is 3
The value is 4
The value is 5
Key Points to Remember:
- while and do...while loops are useful when the number of iterations is not known beforehand.
- for loop is ideal when the number of iterations is known.
- foreach loop is specifically designed to iterate over arrays.
Each loop type has its own use case depending on the specific requirements of the task at hand.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.