温馨提示×

PHP数组操作如何遍历

PHP
小樊
81
2024-11-06 13:32:51
栏目: 编程语言

在PHP中,有多种方法可以用来遍历数组。以下是一些常用的方法:

  1. foreach循环:
<?php
$array = array("apple", "banana", "cherry");

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

$length = count($array);

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

$i = 0;

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

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

array_walk($array, "print_value");
?>
  1. foreach遍历关联数组:
<?php
$array = array(
    "name" => "John",
    "age" => 30,
    "city" => "New York"
);

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

以上就是PHP中常见的遍历数组的方法。

0