How do you print "Queue number 1" through "Queue number 80" without writing 80 lines of echo? Mrs. Tini herself only repeats one sentence: "Queue number 1! Queue number 2! Queue number 3!" The sentence stays the same, only the number goes up, and she stops as soon as the queue is empty.
A loop works in the same way. A loop runs the same code many times, and a value changes on every round (one run of the code). In Mrs. Tini's case, the sentence she repeats is the code, the queue number is the value that changes, and the empty queue is the sign to stop. So in PHP you don't write echo many times: you write one echo inside a loop.
for: repeat as many times as you set
The for loop below prints three queue numbers:
<?php
for ($number = 1; $number <= 3; $number++) {
echo "Queue number $number\n";
}
The result:
Queue number 1
Queue number 2
Queue number 3
The parentheses after for hold three parts, separated by semicolons:
$number = 1: the starting value, run once before the first round.$number <= 3: the condition, checked before every round. While it istrue, the code inside the curly braces{ }runs.$number++: the step, run after every round.++means add 1.- One more thing:
"\n"at the end of the text starts a new line, so each number gets its own line.
| Round | $number |
$number <= 3 |
What happens |
|---|---|---|---|
| 1 | 1 | true |
print Queue number 1, then $number becomes 2 |
| 2 | 2 | true |
print Queue number 2, then $number becomes 3 |
| 3 | 3 | true |
print Queue number 3, then $number becomes 4 |
| - | 4 | false |
the loop stops |
The condition is checked 4 times, but only 3 lines are printed. The fourth check gives false, and that check is what stops the loop.
Guess before reading on: what does for ($i = 0; $i < 3; $i++) { echo $i; } print?
The answer is 012. $i starts at 0, and $i < 3 is already false when $i becomes 3, so 3 is not printed. There is no space or "\n", so the three numbers are printed with nothing between them.
while: repeat as long as the condition holds
The while loop below lowers the fried rice stock until none is left:
<?php
$stock = 3;
while ($stock > 0) {
echo "Stock left: $stock\n";
$stock--;
}
echo "Fried rice is sold out!\n";
Stock left: 3
Stock left: 2
Stock left: 1
Fried rice is sold out!
while (condition)checks its condition before every round, exactly like the middle part offor. The difference: the parentheses ofwhilehold no starting value and no step.$stock--means subtract 1. Without this line,$stockstays 3 forever, the condition is alwaystrue, and the loop never stops. On a server, PHP stops the loop after 30 seconds:
Fatal error: Maximum execution time of 30 seconds exceeded in /app/stall.php on line 5
In a terminal (php stall.php), there is no such time limit. Stop the loop by pressing Ctrl+C.
Use for when the number of rounds is known. Use while when you only know when to stop.
foreach: go through an array one item at a time
The array $menu below holds three menu items, and foreach prints them one by one:
<?php
$menu = ["Fried Rice", "Chicken Noodles", "Iced Tea"];
foreach ($menu as $name) {
echo $name . "\n";
}
foreach takes the items of $menu one by one from the front. On each round, $name holds one menu item: "Fried Rice", then "Chicken Noodles", then "Iced Tea". The loop stops by itself when there are no items left, so there is no condition to get wrong. That's why foreach is the loop used most for arrays.
When you need each item's key too, write $key => $value. In this code, the key goes into $name (the menu item) and the value into $price:
<?php
$prices = ["Fried Rice" => 15, "Chicken Noodles" => 12, "Iced Tea" => 5];
foreach ($prices as $name => $price) {
echo "$name: \$$price\n";
}
Fried Rice: $15
Chicken Noodles: $12
Iced Tea: $5
In an indexed array, the keys are the indexes: 0, 1, 2.
break and continue
The code below uses both:
<?php
$prices = ["Fried Rice" => 15, "Chicken Noodles" => 12, "Iced Tea" => 5, "Crackers" => 2];
foreach ($prices as $name => $price) {
if ($name === "Chicken Noodles") {
continue; // Chicken Noodles is sold out: skip it, go on to the next round
}
if ($price < 5) {
break; // stop completely, the remaining items are not processed
}
echo "$name: \$$price\n";
}
Fried Rice: $15
Iced Tea: $5
continueskips the rest of this round, then the loop continues with the next item. Here Chicken Noodles is skipped, so it is not printed.breakleaves the loop right away. The price of Crackers ($2) is below 5, so Crackers triggersbreak, and the loop ends there. Iced Tea ($5) is still printed, because5 < 5isfalse.- In nested loops (a loop inside a loop),
breakonly leaves the innermost loop.break 2leaves two levels at once.
⚠️ Loops that never stop, or stop too soon
- A while that never stops. Forgetting
$stock--(or a similar step) keeps the conditiontrueforever. <when you meant<=.for ($i = 1; $i < 10; $i++)only goes up to 9. For 1 to 10, write$i <= 10.- A semicolon after the
forparentheses. Infor ($i = 1; $i <= 3; $i++); { echo $i; }, that semicolon ends the loop. The loop repeats with nothing to run until$ibecomes 4. After that, the code in{ }runs once and prints4. - Changing the array through
$price.$priceis only a copy of the value, so$price = $price + 1;insideforeachdoesn't change$prices. Write$prices[$name] = $price + 1;.
TL;DR: A loop runs the code inside curly braces many times, and one run is called a round. for (start; condition; step) is for a known number of rounds: the condition is checked before every round, and the last check, the one that gives false, stops the loop. while (condition) repeats as long as the condition is true: the code inside it must change something, so the condition becomes false at some point. foreach ($array as $value) or foreach ($array as $key => $value) goes through the items of an array one by one until none are left ($key holds the key). continue skips the rest of one round, break leaves the loop. Print "\n" so each result gets its own line.
⚡ for: repeat as many times as you set
Write:
<?php
for ($number = 1; $number <= 3; $number++) {
echo "Queue number $number\n";
}
Guess first: this loop prints 3 lines. The condition $number <= 3 is checked before every round (one run of the code inside { }). How many times is it checked?
4 times. The fourth check happens when $number is already 4. It gives false, and that check is what stops the loop.
Meaning: A for loop runs the code inside the curly braces many times. The parentheses after for hold the starting value (run once), the condition (checked before every round) and the step (run after every round; ++ means add 1). "\n" gives each number its own line.
⚡ while needs something that changes
Write:
<?php
$stock = 3;
while ($stock > 0) {
echo "Stock left: $stock\n";
$stock--;
}
Meaning: while runs the code inside the curly braces as long as its condition is true. $stock-- subtracts 1 from $stock on every round. Without $stock--, $stock stays 3, the condition is always true, and the loop never stops.
⚡ foreach: one at a time until the end
Write:
<?php
$prices = ["Fried Rice" => 15, "Chicken Noodles" => 12, "Iced Tea" => 5];
foreach ($prices as $name => $price) {
echo "$name: \$$price\n";
}
Meaning: foreach goes through the items of the array $prices one by one. On each round, $name holds the key (the menu item) and $price holds the value (the price). The loop stops by itself when there are no items left. continue skips the rest of one round, and break leaves the loop.