Course Content
About Lesson

PHP Loops

Loops are used to run a block of code several times until a specific condition is met.

The for loop is used when we know ahead of time how many times we want to run the code.

for(initialization; condition; increment/decrement) {
    // code to be executed
}
  • initialization: Set a starting value.
  • condition: The loop will continue as long as this condition is true.
  • increment/decrement: Increase or decrease the value after each iteration.
PHP
<?php
for ($i = 1; $i <= 5; $i++) {
    echo "Number: $i <br>";
}
?>
  • It prints the number from 1 to 5.

The while loop runs as long as the condition is true. It checks the condition before executing the code.

while(condition) {
    // code to be executed
}
PHP
<?php
$i = 1;
while ($i <= 5) {
    echo "Number: $i <br>";
    $i++;
}
?>

The do-while loop is like the while loop, but the code runs at least once, even if the condition is false. This happens because the condition is checked after the code executes.

do {
    // code to be executed
} while (condition);
PHP
<?php
$i = 1;
do {
    echo "Number: $i <br>";
    $i++;
} while ($i <= 5);
?>

The foreach loop is used only for arrays. It loops through each element of the array.

foreach($array as $value) {
    // code to be executed
}
PHP
<?php
$colors = ["Red", "Green", "Blue", "Yellow"];

foreach ($colors as $color) {
    echo "Color: $color <br>";
}
?>
PHP
<?php
$student = [
    "Name" => "John",
    "Age" => 21,
    "Course" => "PHP"
];

foreach ($student as $key => $value) {
    echo "$key: $value <br>";
}
?>