How to reverse the order of an array in PHP

We can reverse the order of the values in an array using the array_reverse() function. This is a built-in PHP function that takes an array as its input and returns a new array having the reverse ordered elements.

This function arranges all the elements of an array in just the opposite order of the given array.

Syntax
array_reverse(array, preserve

Parameter Values

array - Required. Specifies an array
preserve - Optional. Specifies if the function should preserve the keys of the array or not. Possible values:
                true
                false


Example

<?php

 
      $array = array("HTML", "CSS", "JavaScript", "PHP", "jQuery");
      $new_array = array_reverse($array);
      print_r($new_array);

?>

Output

Array ( [0] => jQuery [1] => PHP [2] => JavaScript [3] => CSS [4] => HTML )

Using for loop

We can also reverse the order of the values of the input array using for loop. We just have to specify some conditions within the for loop and then print the values of an array using echo.
Example: Reverse the values of an array using for loop

In the given example, we have reversed the values of the given array name $array using the for loop.

<?php
      $array = array("HTML", "CSS", "JavaScript", "PHP", "jQuery");
      $size = sizeof($array);

      for($i=$size-1; $i>=0; $i--){
          echo $array[$i];
          echo "<br>";
      }
   

?>

Output

jQuery
PHP
JavaScript
CSS
HTML

No comments:

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...