Php

Looping Statements

Looping Statements in PHP

Loops allow you to execute a block of code multiple times, either a set number of times or until a condition is met.


1. while Loop

Executes as long as the condition is true.

php
$i = 1;

while ($i <= 5) {
echo "Number: $i<br>";
$i++;
}


2. do...while Loop

Runs the code at least once, then checks the condition.

php
$i = 1;

do {
echo "Count: $i<br>";
$i++;
} while ($i <= 3);


3. for Loop

Best when you know exactly how many times to loop.

php
for ($i = 0; $i < 5; $i++) {
echo "Loop index: $i<br>";
}

4. foreach Loop

Special loop for arrays — great for looping over lists or associative arrays.

php
$colors = ["red", "green", "blue"];

foreach ($colors as $color) {
echo "Color: $color<br>";
}

With associative arrays:

php
$person = ["name" => "John", "age" => 30];

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


5. Loop Control Statements

Statement Description
break Exits the loop entirely
continue Skips the current iteration, moves to next
php
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) continue;
echo "$i ";
}
// Output: 1 2 4 5

Summary Table

Loop Type Use Case
while When condition is checked first
do...while When loop should run at least once
for When iteration count is known
foreach When working with arrays

Leave a Reply

Your email address will not be published. Required fields are marked *