EZ

Eduzan

Learning Hub

Eduzan
Eduzan / PHP

PHP Loops

Similar to other programming languages, loops in PHP are used to repeatedly execute a block of code multiple times based on a condition. PHP offers several types of loops to handle different situations, including forwhiledo...while, and foreach loops. Let’s explore each of these loops, their syntax, and examples.

Why Use Loops?

Loops are useful for executing code repeatedly, which helps in:

  • Iterating through arrays or other data structures.
  • Performing actions multiple times.
  • Pausing execution until a condition is satisfied.

1. PHP for Loop: The for loop is used when you know in advance how many times you want to execute a block of code. It consists of three parts:

  • Initialization: Sets the initial value of the loop variable.
  • Condition: Evaluates whether the loop should continue.
  • Increment/Decrement: Updates the loop variable after each iteration.

Syntax:

for (Initialization; Condition; Increment/Decrement) {
    // Code to execute
}

Example:

<?php

// Code to demonstrate for loop
for ($num = 10; $num <= 15; $num++) {
    echo $num . " ";
}

?>

Output:

10 11 12 13 14 15

2. PHP while Loop: The while loop is an entry-controlled loop, meaning it first checks the condition before entering the loop. It continues running as long as the condition remains true.

Syntax:

while (condition) {
    // Code to execute
}

Example: Printing numbers from 5 to 9.

<?php

$num = 5;

while ($num <= 9) {
    echo $num . " ";
    $num++;
}

?>

Output:

5 6 7 8 9

3. PHP do...while Loop: The do...while loop is an exit-controlled loop. It executes the code block first and then checks the condition, which means the code will run at least once, regardless of the condition.

Syntax:

do {
    // Code to execute
} while (condition);

Example:

<?php

$num = 20;

do {
    echo $num . " ";
    $num++;
} while ($num <= 25);

?>

Output:

20 21 22 23 24 25

4. PHP foreach Loop: The foreach loop is used to iterate over arrays. For each iteration, it assigns the current array element to a variable and moves on to the next one.

Syntax:

foreach ($array as $value) {
    // Code to execute
}

// or

foreach ($array as $key => $value) {
    // Code to execute
}

Example:

<?php

// foreach loop over a simple array
$arr = array(100, 200, 300, 400);

foreach ($arr as $val) {
    echo $val . " ";
}

echo "\n";

// foreach loop over an associative array
$fruits = array(
    "Apple" => 50,
    "Banana" => 30,
    "Orange" => 20
);

foreach ($fruits as $fruit => $price) {
    echo $fruit . " => " . $price . "\n";
}

?>

Output:

100 200 300 400
Apple => 50
Banana => 30
Orange => 20
End of lesson.