As a programmer, you’ll quickly learn how to work with arrays like a pro. The PHP programming language has a lot of built-in helper functions that make it easier to work with arrays.
In this tutorial, we’ll show you two ways to change the order of items in a PHP foreach loop. Let’s quickly go over what we’re trying to do.
$data = ['a','b','c','d'];
foreach($data as $item) {
echo $item;
}
//OUTPUT: abcd
We have a very simple set of data and a for each loop that goes through it. We want for each loop to read this array backward so that the output is “dcba.” There are several ways to do this.
How to Reverse Order of a ForEach Loop in PHP?
You can use the array reverse method or a different loop and count through the array backward to change the order of a for each loop. Here, we’ll take a close look at both options.
Solution 1 – Use array_reverse
array_reverse is a function that comes with PHP that is very useful. This method will take an array and give back a copy that is backwards. Let’s look at an example of code:
$data = ['a','b','c','d'];
foreach(array_reverse($data) as $item) {
echo $item;
}
//OUTPUT: dcba
We can easily use the array reverse function right in our foreach parameters to switch the order of the items in our primary array before they are spit out.
This is a very clean solution that gets the job done, but it might not be the best.
Since we’ll always know how big the array is, there’s nothing stopping us from reading it backward instead of doing an operation that rearranges a copy of it for no reason. Let’s look at another example, which in some situations might be a better choice.
Solution 2 – Count the Array Backwards
We can also just read the array backward instead of having to rebuild it in the opposite order. But for this solution, we need to change our foreach loop to a while loop.
Let’s look at an example of code:
$data = ['a','b','c','d'];
$index = count($data);
while($index) {
echo $data[--$index];
}
//OUTPUT: dcba
With this solution, we’ll start by counting the array’s elements to get an index. Then we’ll make a while loop with the index as its parameter.
Inside the while loop, we can directly call our first data array and lower the index at the same time. Once the while loop gets to the end of the array, it will automatically stop.
Even though the second solution doesn’t use a foreach loop, it gets the same job done more quickly.
If your project needs a ForEach Loop in PHP to be done in the opposite order, you could use this method.