PHP 中有許多不同的遍歷數組或對象的方法和技巧。以下是一些常見的 PHP 遍歷技巧:
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo $color . "<br>";
}
$person = array("name" => "John", "age" => 30, "city" => "New York");
foreach ($person as $key => $value) {
echo $key . ": " . $value . "<br>";
}
$numbers = array(1, 2, 3, 4, 5);
$i = 0;
while ($i < count($numbers)) {
echo $numbers[$i] . "<br>";
$i++;
}
$fruits = array("apple", "banana", "orange");
for ($i = 0; $i < count($fruits); $i++) {
echo $fruits[$i] . "<br>";
}
$numbers = array(1, 2, 3, 4, 5);
function square($n) {
return $n * $n;
}
$squared_numbers = array_map("square", $numbers);
print_r($squared_numbers);
這些是一些常見的 PHP 遍歷技巧,希望對你有幫助!