Reverse order of foreach list items

To reverse the order of the items in a list when using a foreach loop in PHP, you can simply reverse the array using the array_reverse function before the loop.

For example:

<?php

$items = [1, 2, 3, 4, 5];
$items = array_reverse($items);
foreach ($items as $item) {
  echo $item . "\n";
}

This will output the items in the list in reverse order: 5 4 3 2 1.

Watch a course Learn object oriented PHP

Alternatively, you could use a for loop to iterate over the array in reverse order. This is useful if you only want to reverse the order of the items in the list for a single loop and don't want to modify the original array.

For example:

<?php

$items = [1, 2, 3, 4, 5];
for ($i = count($items) - 1; $i >= 0; $i--) {
  echo $items[$i] . "\n";
}

This will also output the items in the list in reverse order: 5 4 3 2 1.