php遍歷一個(gè)數(shù)組的方法有哪些

PHP
小億
86
2024-02-20 12:21:41

  1. 使用for循環(huán)遍歷數(shù)組:
$array = array("apple", "banana", "cherry");

for($i = 0; $i < count($array); $i++) {
    echo $array[$i] . "<br>";
}
  1. 使用foreach循環(huán)遍歷數(shù)組:
$array = array("apple", "banana", "cherry");

foreach($array as $value) {
    echo $value . "<br>";
}
  1. 使用while循環(huán)遍歷數(shù)組:
$array = array("apple", "banana", "cherry");

$i = 0;
while($i < count($array)) {
    echo $array[$i] . "<br>";
    $i++;
}
  1. 使用array_walk函數(shù)遍歷數(shù)組:
$array = array("apple", "banana", "cherry");

function printItem($item) {
    echo $item . "<br>";
}

array_walk($array, 'printItem');
  1. 使用array_map函數(shù)遍歷數(shù)組:
$array = array("apple", "banana", "cherry");

function addBrackets($item) {
    return $item . "<br>";
}

$newArray = array_map('addBrackets', $array);
foreach($newArray as $value) {
    echo $value;
}

0