Thursday, July 4, 2024
HomeLanguagesPhpHow 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
)

Nicole Veronica Rubhabha
Nicole Veronica Rubhabha
A highly competent and organized individual DotNet developer with a track record of architecting and developing web client-server applications. Recognized as a personable, dedicated performer who demonstrates innovation, communication, and teamwork to ensure quality and timely project completion. Expertise in C#, ASP.Net, MVC, LINQ, EF 6, Web Services, SQL Server, MySql, Web development,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments