In php, you can reverse the items in an array easiest with the array_reverse() function.

$example = array("lion", "bear", "snake", "horse");

$reversed = array_reverse($example);

print_r($reversed);

//Output:
Array
(
    [0] => horse
    [1] => snake
    [2] => bear
    [3] => lion
)

When working with arrays and collections of data in php, it is useful to be able to easily change and manipulate our data structures easily.

One such operation is to be able to reverse an array.

To reverse an array in php, we can use the php array_reverse() function.

array_reverse() takes an array and returns the reverse of the given array.

Below is an example of how to use array_reverse() to reverse an array in php.

$example = array("lion", "bear", "snake", "horse");

$reversed = array_reverse($example);

print_r($reversed);

//Output:
Array
(
    [0] => horse
    [1] => snake
    [2] => bear
    [3] => lion
)

Preserving the Keys when Reversing an Array in php with array_reverse()

When reversing an array, by default, the numeric keys are updated. For example, above, we had an array of 4 items. After reversing, the item that previously was last, and had a key value of ‘3’, had a key value of ‘0’.

You can pass a second argument to array_reverse() to preserve the numeric keys after reversing the array.

Just pass ‘true’ after the array you want to reverse in your call to array_reverse() to preserve the keys.

Below is an example of how to use array_reverse() to reverse an array and preserve the numeric keys in php.

$example = array("lion", "bear", "snake", "horse");

$reversed = array_reverse($example, true);

print_r($reversed);

//Output:
Array
(
    [3] => horse
    [2] => snake
    [1] => bear
    [0] => lion
)

How to Reverse an Array without array_reverse() in php

If you want to reverse an array without a function in php, you can also use a loop.

To use a for loop for reversing an array without the reverse() function, we will swap items in the list in the following way.

First, we swap the first and last items. Next, we continue with swapping the second and second to last items, then the third and third to last items, until we reach the middle of the list.

Below is an example of how to use a loop to reverse an array in php.

$example = array("lion", "bear", "snake", "horse");

foreach(range(0,count($example)/2) as $i) {
    [$example[$i], $example[count($example) - $i - 1]]= [$example[count($example) - $i - 1],$example[$i]];
}

print_r($example);

//Output:
Array
(
    [0] => horse
    [1] => snake
    [2] => bear
    [3] => lion
)

Hopefully this article has been useful for you to learn how to use php to reverse arrays.

Categorized in:

PHP,

Last Update: February 26, 2024