PHP LOOPS
Types of Loops in PHP:
• for loop
• while loop
• do-while loop
• foreach loop
For Loop
for (initialization; condition; increment) {
// code to be executed
}
For Loop
<?php
for ($i = 0; $i < 5; $i++) {
echo "The number is: $i <br>";
} ?>
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
These operators are used to combine multiple conditions.
•&& (AND): True if both conditions are true.
•|| (OR): True if at least one condition is true.
•! (NOT): Inverts the truthiness of a condition.
&& AND Operator
• $age = 25;
$has_license = true;
if ($age >= 18 && $has_license) {
echo "You can drive.";
} else {
echo "You cannot drive."; }
|| OR Operator
$age = 17;
$has_permission = true;
if ($age >= 18 || $has_permission) {
echo "You can attend the event.";
} else {
echo "You cannot attend the event."; }