PHP Loops
Online resources
Key concepts to understand
-
Reasons to be mindful of infinite loops
-
while() Loops
<?php
$a = 0;
while($a < 10) {
echo $a;
$a = $a + 1;
}
?>
- for() Loops
<?php
// Same behavior as the while loop
for($a=0; $a < 10; $a++) {
echo $a;
}
?>
- foreach() Loops
- Used with arrays and loops through all elements in order
- Each element is assigned to a temporary variable
<?php
$colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'];
foreach($colors as $color) {
echo $color;
}
?>
* Associative arrays assign key and value to temporary variables
<?php
$color_fruit = ['red' => 'apple', 'orange' => 'orange', 'yellow' => 'lemon', 'green' => 'lime', 'purple' => 'plum'];
foreach($colors as $color => $fruit) {
echo "{$fruit} is {$color}.";
}
?>
- continue, break
- Continue skips immediately to the start of the next loop
- Break immediately stops all looping