To iterate over an array in PHP in reverse order, you can use a for
loop starting from the last index to the first index or the array_reverse
function.
In this example,
$numbers
with some values.for
loop starting from the last index to iterate over each element of the array in reverse order.<?php
$numbers = [1, 2, 3, 4, 5];
for ($i = count($numbers) - 1; $i >= 0; $i--) {
echo $numbers[$i] . "\n";
}
?>
5 4 3 2 1
In this example,
$fruits
with some values.foreach
loop with the array_reverse
function to iterate over each element of the array in reverse order.<?php
$fruits = ['apple', 'banana', 'cherry'];
foreach (array_reverse($fruits) as $fruit) {
echo $fruit . "\n";
}
?>
cherry banana apple
In this tutorial, we learned How to Iterate Over an Array in Reverse Order in PHP language with well detailed examples.