溫馨提示×

學會這些php遍歷技巧

PHP
小樊
116
2024-07-25 23:14:12
欄目: 編程語言

PHP 中有許多不同的遍歷數組或對象的方法和技巧。以下是一些常見的 PHP 遍歷技巧:

  1. 使用 foreach 循環遍歷數組:
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
    echo $color . "<br>";
}
  1. 使用 foreach 循環遍歷關聯數組:
$person = array("name" => "John", "age" => 30, "city" => "New York");
foreach ($person as $key => $value) {
    echo $key . ": " . $value . "<br>";
}
  1. 使用 while 循環遍歷數組:
$numbers = array(1, 2, 3, 4, 5);
$i = 0;
while ($i < count($numbers)) {
    echo $numbers[$i] . "<br>";
    $i++;
}
  1. 使用 for 循環遍歷數組:
$fruits = array("apple", "banana", "orange");
for ($i = 0; $i < count($fruits); $i++) {
    echo $fruits[$i] . "<br>";
}
  1. 使用 array_map 函數遍歷數組:
$numbers = array(1, 2, 3, 4, 5);
function square($n) {
    return $n * $n;
}
$squared_numbers = array_map("square", $numbers);
print_r($squared_numbers);

這些是一些常見的 PHP 遍歷技巧,希望對你有幫助!

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女