What are the recommended methods for iterating through arrays and displaying values in PHP?
When iterating through arrays in PHP, the most common methods are using a foreach loop or a for loop. The foreach loop is particularly useful for iterating through arrays with unknown or varying lengths, as it automatically handles the array keys. The for loop is useful when you need to iterate through an array with a known length and want more control over the iteration process.
// Using a foreach loop to iterate through an array
$fruits = array("apple", "banana", "orange");
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
// Using a for loop to iterate through an array
$numbers = array(1, 2, 3, 4, 5);
for ($i = 0; $i < count($numbers); $i++) {
echo $numbers[$i] . "<br>";
}