PHP中遍歷數(shù)組的方法有以下幾種:
$colors = array("red", "green", "blue");
foreach($colors as $color) {
echo $color . "<br>";
}
$colors = array("red", "green", "blue");
$length = count($colors);
for($i = 0; $i < $length; $i++) {
echo $colors[$i] . "<br>";
}
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
reset($age);
while (list($key, $value) = each($age)) {
echo $key . " is " . $value . " years old<br>";
}
function myfunction($value, $key) {
echo "$key: $value<br>";
}
$colors = array("red", "green", "blue");
array_walk($colors, "myfunction");
function myfunction($value) {
return $value * $value;
}
$numbers = array(1, 2, 3, 4, 5);
$new_numbers = array_map("myfunction", $numbers);
print_r($new_numbers);