PHP中遍歷數組的方法有以下幾種:
$array = [1, 2, 3, 4, 5];
foreach ($array as $value) {
echo $value;
}
$array = [1, 2, 3, 4, 5];
$length = count($array);
for ($i = 0; $i < $length; $i++) {
echo $array[$i];
}
$array = ['name' => 'John', 'age' => 25, 'city' => 'New York'];
reset($array);
while (list($key, $value) = each($array)) {
echo $key . ': ' . $value;
}
$array = [1, 2, 3, 4, 5];
function square($value) {
return $value * $value;
}
$result = array_map('square', $array);
print_r($result);
$array = [1, 2, 3, 4, 5];
function cube(&$value) {
$value = $value * $value * $value;
}
array_walk($array, 'cube');
print_r($array);