Friday, November 21, 2025
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
32405 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6781 POSTS0 COMMENTS
Nicole Veronica
11928 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11995 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7166 POSTS0 COMMENTS
Thapelo Manthata
6862 POSTS0 COMMENTS
Umr Jansen
6847 POSTS0 COMMENTS