AnyCompiler

Loops

for and while in PHP look exactly like their C/Java/JavaScript counterparts. foreach is where PHP diverges in a genuinely useful way: foreach ($array as $value) walks every value in an indexed array, and foreach ($array as $key => $value) walks every key/value pair — which, since an associative array's keys aren't necessarily 0, 1, 2, ..., is the normal way to iterate one.

<?php
for ($i = 1; $i <= 5; $i++) {
    echo $i, " ";
}
echo "\n";

$i = 0;
while ($i < 3) {
    echo "spin $i\n";
    $i++;
}

$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $index => $fruit) {
    echo "$index: $fruit\n";
}

$prices = ["apple" => 1.5, "banana" => 0.5];
foreach ($prices as $name => $price) {
    echo "$name costs $price\n";
}
Output
1 2 3 4 5 
spin 0
spin 1
spin 2
0: apple
1: banana
2: cherry
apple costs 1.5
banana costs 0.5

The first foreach ran over an indexed array, so $index came out as the familiar 0, 1, 2; the second ran over an associative array, and $name came out as "apple" and "banana" — the actual string keys, not a position. Same foreach ... as $key => $value syntax both times, because under the hood it's the same array type either way. Next: functions — default arguments, variadic (...) arguments, and return type declarations.

Practice exercise

Use a for loop to sum the integers 1 through 10 (inclusive) into $total, then echo $total.