To reverse an array in php without a function, we can use a loop and swap items in order.

$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
)

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.

We can use the php array_reverse() function, but sometimes you want to be able to perform operations without the use of built-in functions.

We can use the square bracket syntax for array destructuring assignment in a loop to swap items in a php array and reverse the array.

Implemented in php version 7.1, we can unpack arrays and use them to assign to other arrays and variables.

With this in mind, we can use a loop to reverse an array without the help of another function or without other variables easily in php.

To use a for loop for reversing a list without the array_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.

$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 reverse an array in php without using another function or variable.

Categorized in:

PHP,

Last Update: February 26, 2024