PHP Loops (while, do-while, for, foreach)
Loops let you run the same block of code multiple times, which is essential for processing lists of data or repeating a task until a condition is met. PHP provides while, do-while, for, and foreach loops.
while checks its condition before each iteration, do-while checks it after (guaranteeing at least one run), for is ideal when you know how many times to loop, and foreach is designed specifically for looping through arrays.
for ($i = 0; $i < 5; $i++) { }
foreach ($array as $value) { }while and do-while
while (condition) { } repeats as long as the condition is true, checked before each pass. do { } while (condition); runs the block once first, then checks the condition.
for and foreach
for (init; condition; increment) { } is useful for counting loops with a known number of iterations. foreach ($array as $value) { } iterates over every element of an array.
<?php
for ($i = 1; $i <= 3; $i++) {
echo $i . " ";
}
?>1 2 3 The for loop runs three times, printing i each time before incrementing.
<?php
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
echo $fruit . " ";
}
?>apple banana cherry foreach visits each element of the array in order, without needing an index.
Key points
- while checks its condition before running the loop body.
- do-while always runs the loop body at least once.
- for is ideal when the number of iterations is known in advance.
- foreach is the simplest way to loop through arrays.
