Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • PHP Tutorial
  • PHP Exercises
  • PHP Array
  • PHP String
  • PHP Calendar
  • PHP Filesystem
  • PHP Math
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP GMP
  • PHP IntlChar
  • PHP Image Processing
  • PHP DsSet
  • PHP DsMap
  • PHP Formatter
  • Web Technology
Open In App
Next Article:
How to check an element is exists in array or not in PHP ?
Next article icon

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

Last Updated : 03 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 : 

Table of Content

  • Using for Loop
  • Using array_reverse() Method
  • Using the array_reduce Function
  • Using array_walk()
  • Using Stack (array_push and array_pop)
  • Using the array_reduce Function

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); ?> 

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 )

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 )

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);  ?> 

Output
Array (     [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 ) ?> 

Output
Array (     [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);  ?> 

Output
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 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);  ?> 

Output
Array (     [0] => s     [1] => k     [2] => e     [3] => e     [4] => G ) 

Next Article
How to check an element is exists in array or not in PHP ?

Y

yashkumar0457
Improve
Article Tags :
  • Web Technologies
  • PHP
  • PHP-array
  • PHP-function
  • PHP-Questions

Similar Reads

  • How to check an element is exists in array or not in PHP ?
    An array may contain elements belonging to different data types, integer, character, or logical type. The values can then be inspected in the array using various in-built methods : Approach 1 (Using in_array() method): The array() method can be used to declare an array. The in_array() method in PHP
    2 min read
  • How to Insert a New Element in an Array in PHP ?
    In PHP, an array is a type of data structure that allows us to store similar types of data under a single variable. The array is helpful to create a list of elements of similar types, which can be accessed using their index or key. We can insert an element or item in an array using the below functio
    5 min read
  • 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 approaches Table of Content Using array_search() FunctionUsing array_flip()Using a custom functionUsing a foreach LoopUsing array_keys FunctionUsing
    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
  • How to sort an array in descending order in Ruby?
    In this article, we will discuss how to sort an array in descending order in ruby. We can sort an array in descending order through different methods ranging from using sort the method with a block to using the reverse method after sorting in ascending order Table of Content Sort an array in descend
    3 min read
  • Removing Array Element and Re-Indexing in PHP
    In order to remove an element from an array, we can use unset() function which removes the element from an array, and then use array_values() function which indexes the array numerically automatically. Function Usedunset(): This function unsets a given variable. Syntax:void unset ( mixed $var [, mix
    2 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 Content Usi
    3 min read
  • Find the Second Largest Element in an Array in PHP
    We will be given with an integer array, i.e. $array1 or $ array2, and the task is to find the second largest element in the array. There are multiple ways to approach and solve this problem however using sorting is the most common and concise approach as we use the rsort() function for further opera
    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 Second most frequent element in an array
    Given an array we have to find the second most frequent element present in it. Examples: Input : array(3, 3, 4, 5, 5, 5, 9, 8, 8, 8, 8, 8); Output : Second most frequent element is: 5 Input : array("geeks", "for", "geeks"); Output : Second most frequent element is: for Here are some common approache
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences