Spex3
    

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
}


✅ Example: Counting from 1 to 5


<?php
for ($i = 1; $i <= 5; $i++) {
echo "Number: $i
";
}
?>


📌 Output:


Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

2. while Loop
The while loop runs as long as the condition is true.

✅ Syntax:


while (condition) {
// Code to execute
}


✅ Example: Counting from 1 to 5



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


📌 This loop executes while $i is less than or equal to 5.

3. do-while Loop
The do-while loop is similar to while, but it executes at least once, even if the condition is false.

✅ Syntax:


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


✅ Example:


<?php
$i = 1;
do {
echo "Number: $i
";
$i++;
} while ($i <= 5);
?>


📌 The block executes once, then checks the condition.

✅ Example: Condition Fails Initially


<?php
$i = 10;
do {
echo "This will print at least once!
";
} while ($i < 5);
?>


📌 Even though $i is already greater than 5, the loop runs once.

4. foreach Loop
The foreach loop is specifically used for iterating over arrays.

✅ Syntax (Indexed Array):


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


✅ Example:


<?php
$fruits = ["Apple", "Banana", "Cherry"];

foreach ($fruits as $fruit) {
echo "$fruit
";
}
?>


📌 Output:


Apple
Banana
Cherry

✅ Syntax (Associative Array):


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


✅ Example:


<?php
$person = ["Name" => "John", "Age" => 25, "City" => "New York"];

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


📌 Output:


Name: John
Age: 25
City: New York
Loop Control Statements
break → Stops the loop immediately.

continue → Skips the current iteration and moves to the next one.

✅ Example (break):


<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 6) {
break; // Stops when $i is 6
}
echo "$i
";
}
?>


📌 Output:


1
2
3
4
5

✅ Example (continue):


<?php
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue; // Skips 3
}
echo "$i
";
}
?>


📌 Output:


1
2
4
5

Conclusion
Use for when the number of iterations is known.

Use while when looping until a condition is met.

Use do-while when the loop must execute at least once.

Use foreach for arrays.


    Date: 2025-03-28 00:00:00.000000