How to get elements in reverse order of an array in PHP ?
Last Updated :
03 Jul, 2024
An array is a collection of elements stored together. Every element in an array belong to a similar data type. The elements in the array are recognized by their index values. The elements can be subjected to a variety of operations, including reversal.
There are various ways to reverse the elements of an array :
Using for Loop
Using for Loop, a decrement for loop can be initiated in order to access the elements in the reverse order. The index begins at the length of the array - 1 until it reaches the beginning of the array. During each iteration, the inbuilt array_push method is called, which is used to push the elements to the newly declared array maintained for storing reverse contents.
Syntax:
array_push($array, $element)
PHP
<?php
// Declaring an array
$arr = array(1, 2, 3, 4, 5);
echo("Original Array : ");
print_r($arr);
// Declaring an array to store reverse
$arr_rev = array();
for($i = sizeof($arr) - 1; $i >= 0; $i--) {
array_push($arr_rev,$arr[$i]);
}
echo("Modified Array : ");
print_r($arr_rev);
?>
OutputOriginal Array : Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Modified Array : Array
(
[0] => 5
[1] => 4
[2] => 3
[3] => 2
[4] => 1
)
Using array_reverse() Method
the array_reverse() function can be used to reverse the contents of the specified array. The output is also returned in the form of an array.
Syntax:
array_reverse($array)
PHP
<?php
// Declaring an array
$arr = array(1, 2, 3, 4, 5);
echo("Original Array : ");
print_r($arr);
// Reversing array
$arr_rev = array_reverse($arr);
echo("Modified Array : ");
print_r($arr_rev);
?>
OutputOriginal Array : Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Modified Array : Array
(
[0] => 5
[1] => 4
[2] => 3
[3] => 2
[4] => 1
)
Using the array_reduce Function
The array_reduce function can reverse an array by iteratively prepending each element to a new array. This method processes the original array and constructs a reversed version by adding each item to the front of the new array.
Example:
PHP
<?php
$array = [1, 2, 3, 4, 5];
$reversedArray = array_reduce($array, function($carry, $item) {
array_unshift($carry, $item);
return $carry;
}, []);
print_r($reversedArray);
?>
OutputArray
(
[0] => 5
[1] => 4
[2] => 3
[3] => 2
[4] => 1
)
Using array_walk()
In PHP, array_walk() iterates through an array and applies a callback function to each element. To reverse an array using array_walk(), prepend each element to a new array using array_unshift() within the callback function.
Example
PHP
<?php
$array = [1, 2, 3, 4, 5];
$reversedArray = [];
array_walk($array, function($item) use (&$reversedArray) {
array_unshift($reversedArray, $item);
});
print_r($reversedArray); // Output: Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1 )
?>
OutputArray
(
[0] => 5
[1] => 4
[2] => 3
[3] => 2
[4] => 1
)
Using Stack (array_push and array_pop)
This method involves using the stack data structure, where elements are pushed onto the stack and then popped off in the reverse order.
Example: In this example, the reverseArray function initializes an empty stack and an empty array to hold the reversed elements. It then iterates through the input array, pushing each element onto the stack. After all elements are on the stack, the function repeatedly pops elements from the stack and appends them to the reversed array.
PHP
<?php
function reverseArray($array) {
$stack = [];
$reversedArray = [];
// Push all elements onto the stack
foreach ($array as $element) {
array_push($stack, $element);
}
// Pop all elements from the stack to form the reversed array
while (!empty($stack)) {
$reversedArray[] = array_pop($stack);
}
return $reversedArray;
}
$arr = [1, 2, 3, 4, 5];
$reversedArr = reverseArray($arr);
print_r($reversedArr);
?>
OutputArray
(
[0] => 5
[1] => 4
[2] => 3
[3] => 2
[4] => 1
)
Using the array_reduce Function
The array_reduce function can reverse an array by iteratively prepending each element to a new array. This method processes the original array and constructs a reversed version by adding each item to the front of the new array.
Example:
PHP
<?php
function reverseArrayUsingReduce($array) {
return array_reduce($array, function($carry, $item) {
array_unshift($carry, $item);
return $carry;
}, []);
}
$array = ['G', 'e', 'e', 'k', 's'];
$reversed_array = reverseArrayUsingReduce($array);
print_r($reversed_array);
?>
OutputArray
(
[0] => s
[1] => k
[2] => e
[3] => e
[4] => G
)
Similar Reads
How to find the index of an element in an array using PHP ? In this article, we will discuss how to find the index of an element in an array in PHP. Array indexing starts from 0 to n-1. Here we have some common approachesTable of ContentUsing array_search() FunctionUsing array_flip()Using a custom functionUsing a foreach LoopUsing array_keys FunctionUsing ar
6 min read
How to Check an Array is Sorted or Not in PHP? Given an array, the task is to check whether the given array is sorted or not. Arrays are often used to store and manipulate data. One common task is to check if an array is sorted in ascending or descending order. This article will explore different approaches to determine whether an array is sorte
3 min read
Remove First Element from an Array in PHP Given an array, the task is to remove the first element from an array in PHP. Examples:Input: arr = [1, 2, 3, 4, 5, 6, 7]; Output: 2, 3, 4, 5, 6, 7 Input: arr = [3, 4, 5, 6, 7, 1, 2] Output: 4, 5, 6, 7, 1, 2Below are the methods to remove the first element from an array in PHP:Table of ContentUsing
3 min read
How to Switch the First Element of an Arrays Sub Array in PHP? Given a 2D array where each element is an array itself, your task is to switch the first element of each sub-array with the first element of the last sub-array using PHP.Example:Input: num = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']];Output: [ ['g', 'b', 'c'], ['d', 'e', 'f'], ['a', 'h', '
2 min read
PHP Sort array of strings in natural and standard orders You are given an array of strings. You have to sort the given array in standard way (case of alphabets matters) as well as natural way (alphabet case does not matter).Input : arr[] = {"Geeks", "for", "geeks"}Output : Standard sorting: Geeks for geeks Natural sorting: for Geeks geeks Input : arr[] =
2 min read
PHP Sort array of strings in natural and standard orders You are given an array of strings. You have to sort the given array in standard way (case of alphabets matters) as well as natural way (alphabet case does not matter).Input : arr[] = {"Geeks", "for", "geeks"}Output : Standard sorting: Geeks for geeks Natural sorting: for Geeks geeks Input : arr[] =
2 min read