How to use foreach
loops to work with arrays
A foreach loop that displays the values in an associative array
$tax_rates = array('NC' => 7.75, 'CA' => 8.25, 'NY' => 8.875);
echo("<ul>\n");
foreach ($tax_rates as $rate) {
echo("<li>$rate</li>\n");
}
echo("</ul>");
-->
A foreach loop that displays the keys and values
echo("<ul>\n");
foreach ($tax_rates as $state => $rate) {
echo("<li>$state ($rate)</li>\n");
}
echo("</ul>");
}
- NC (7.75)
- CA (8.25)
- NY (8.875)
A foreach loop that displays the values in a regular array
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
unset($numbers[2], $numbers[6]);
$numbers_string = '';
foreach($numbers as $number) {
$numbers_string .= $number . ' ';
}
echo($numbers_string); // Displays: 1 2 4 5 6 8 9 10
1 2 4 5 6 8 9 10
- You can use a foreach statement to create a foreach loop that accesses only those elements in an array that are defined.
Back