Chapter 4 PHP Loops
Chapter 4 PHP Loops
Explanation:
Initialization: $i = 0 (starting value).
Condition: $i < 5 (loop runs while this is true).
Increment: $i++ (increase by 1 after each iteration).
While Loop
while (condition) {
// code to be executed
}
While Loop
<?php
$i = 0;
while ($i < 5) {
echo "The number is: $i <br>";
$i++;
}
?>
Do-While Loop
• do {
// code to be executed
} while (condition);
Do-While Loop
• <?php
$i = 0;
do {
echo "The number is: $i <br>";
$i++;
} while ($i < 5);
?>
Explanation:
• The code is executed at least once, even if the condition is false.
Foreach Loop (For Arrays)
• foreach ($array as $value) {
// code to be executed ;
}
Foreach Loop (For Arrays)
<?php
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo "$color <br>";
}
?>
Explanation:
• Iterates over each element in the array.
• $color holds the value of each element during iteration.
Break and Continue
BREAK
Exits the loop when a certain condition is met.
<?php
for ($i = 0; $i < 10; $i++) {
if ($i == 5) {
break;
}
echo "The number is: $i <br>";
}
?>
Break and Continue
Continue
Skips the current iteration when a certain condition is met.
<?php
for ($i = 0; $i < 10; $i++) {
if ($i == 5) {
continue;
} echo "The number is: $i <br>";
}
?>
Common Mistakes and Best
Practices
•Infinite Loops:
•Ensure the loop's condition will eventually be false.
•Off-by-One Errors:
•Be cautious with loop conditions to avoid skipping or exceeding boundaries.
•Break Complex Loops:
•Use break or continue wisely for better performance.
Logical Operators