PHP數(shù)組操作如何遍歷

PHP
小樊
81
2024-11-06 13:32:51

在PHP中,有多種方法可以用來(lái)遍歷數(shù)組。以下是一些常用的方法:

  1. foreach循環(huán):
<?php
$array = array("apple", "banana", "cherry");

foreach ($array as $value) {
    echo $value . "<br>";
}
?>
  1. for循環(huán):
<?php
$array = array("apple", "banana", "cherry");

$length = count($array);

for ($i = 0; $i < $length; $i++) {
    echo $array[$i] . "<br>";
}
?>
  1. while循環(huán):
<?php
$array = array("apple", "banana", "cherry");

$i = 0;

while ($i < count($array)) {
    echo $array[$i] . "<br>";
    $i++;
}
?>
  1. array_walk()函數(shù):
<?php
function print_value(&$value, $key) {
    echo $key . ": " . $value . "<br>";
}

$array = array("apple", "banana", "cherry");

array_walk($array, "print_value");
?>
  1. foreach遍歷關(guān)聯(lián)數(shù)組:
<?php
$array = array(
    "name" => "John",
    "age" => 30,
    "city" => "New York"
);

foreach ($array as $key => $value) {
    echo $key . ": " . $value . "<br>";
}
?>

以上就是PHP中常見(jiàn)的遍歷數(shù)組的方法。

0