PHP Loops: for, while, do-while, foreach

PHP Loops: for, while, do-while, foreach
Loops in PHP are used to execute a block of code multiple times. The main types of loops in PHP are:
for loop – Used when the number of iterations is known.
while loop – Runs as long as a condition is true.
do-while loop – Runs at least once, then continues based on a condition.
foreach loop – Used to iterate through arrays.
1. for Loop
The for loop is used when we know how many times we want to iterate.
✅ Syntax:
for (initialization; condition; increment/decrement) {
// Code to execute
}
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Number: $i
";
}
?>
while (condition) {
// Code to execute
}
<?php
$i = 1;
while ($i <= 5) {
echo "Number: $i
";
$i++;
}
?>
do {
// Code to execute
} while (condition);
<?php
$i = 1;
do {
echo "Number: $i
";
$i++;
} while ($i <= 5);
?>
<?php
$i = 10;
do {
echo "This will print at least once!
";
} while ($i < 5);
?>
foreach ($array as $value) {
// Code to execute
}
<?php
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo "$fruit
";
}
?>
foreach ($array as $key => $value) {
// Code to execute
}
<?php
$person = ["Name" => "John", "Age" => 25, "City" => "New York"];
foreach ($person as $key => $value) {
echo "$key: $value
";
}
?>
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 6) {
break; // Stops when $i is 6
}
echo "$i
";
}
?>
<?php
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue; // Skips 3
}
echo "$i
";
}
?>
Date: 2025-03-28 00:00:00.000000