Runs while the condition is true
while (condition) {
// code block
}$i = 1;
while ($i <= 5) {
echo $i . " ";
$i++;
}Runs once before checking the condition
do {
// code block
} while (condition);
$i = 1;
do {
echo $i . " ";
$i++;
} while ($i <= 5);Good when the number of iterations is known
for (initialization; condition; update) {
// code block
}for ($i = 0; $i < 5; $i++) {
echo $i . " ";
}The foreach loop is a special loop used to iterate over arrays and collections in PHP. It automatically goes through each element in the array without needing to manage a counter manually.
It's ideal when working with lists or associative arrays, as it gives direct access to the elements (and optionally keys) of the array.
Iterate through a simple indexed array
This loop goes through each value in the $colors array and stores it in $color, which is used in the loop body.
Iterate through an associative array to get both keys and values
Here, $name gets the key (like "Alice") and $age gets the value (like 25) during each iteration.
Best Practice: Use foreach when you want to go through every item in an array without modifying the array index manually.
break exits the loop immediately:
for ($i = 0; $i < 10; $i++) {
if ($i == 5) break;
echo $i . " ";
}continue skips to the next iteration:
for ($i = 0; $i < 5; $i++) {
if ($i == 2) continue;
echo $i . " ";
}Ask the AI if you need help understanding or want to dive deeper in any topic