在PHP中,有多種方法可以用來(lái)遍歷數(shù)組。以下是一些常用的方法:
<?php
$array = array("apple", "banana", "cherry");
foreach ($array as $value) {
echo $value . "<br>";
}
?>
<?php
$array = array("apple", "banana", "cherry");
$length = count($array);
for ($i = 0; $i < $length; $i++) {
echo $array[$i] . "<br>";
}
?>
<?php
$array = array("apple", "banana", "cherry");
$i = 0;
while ($i < count($array)) {
echo $array[$i] . "<br>";
$i++;
}
?>
<?php
function print_value(&$value, $key) {
echo $key . ": " . $value . "<br>";
}
$array = array("apple", "banana", "cherry");
array_walk($array, "print_value");
?>
<?php
$array = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
foreach ($array as $key => $value) {
echo $key . ": " . $value . "<br>";
}
?>
以上就是PHP中常見(jiàn)的遍歷數(shù)組的方法。