Arrays and Iteration
Foreach Keys
Associative arrays let foreach read both the key and the value for each entry.
Foreach Keys
foreach_keys.php
<?php
$minimum = ;
$matches = 0;
$total = 0;
foreach (["left" => 3, "middle" => 5, "right" => 7] as $name => $amount) {
if ($amount >= $minimum) {
$matches = $matches + 1;
$total = $total + $amount;
}
}
echo "minimum=" . $minimum . "\n";
echo "matches=" . $matches . "\n";
echo "total=" . $total . "\n";
<?php
$minimum = ;
$matches = 0;
$total = 0;
foreach (["left" => 3, "middle" => 5, "right" => 7] as $name => $amount) {
if ($amount >= $minimum) {
$matches = $matches + 1;
$total = $total + $amount;
}
}
echo "minimum=" . $minimum . "\n";
echo "matches=" . $matches . "\n";
echo "total=" . $total . "\n";
<?php
$minimum = ;
$matches = 0;
$total = 0;
foreach (["left" => 3, "middle" => 5, "right" => 7] as $name => $amount) {
if ($amount >= $minimum) {
$matches = $matches + 1;
$total = $total + $amount;
}
}
echo "minimum=" . $minimum . "\n";
echo "matches=" . $matches . "\n";
echo "total=" . $total . "\n";
associative iteration
When iterating an associative array, the loop can receive both the key and its matching value.