Wednesday, June 17, 2026
HomeLanguagesHow to get elements in reverse order of an array in PHP...

How to get elements in reverse order of an array in PHP ?

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 : 

Approach 1: 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);
?>


Output

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

Approach 2 : 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);
?>


Output

Original 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
)
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32516 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6898 POSTS0 COMMENTS
Nicole Veronica
12014 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS