W3docs

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.

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:

Example of reversing order of foreach list items in PHP

php— editable, runs on the server

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

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:

Example of reversing order of list items with a for loop in PHP

php— editable, runs on the server

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