PHP Array Function : array_reverse()

The array_reverse() function used to reverse the order of elements on the array. The syntax is as follows :
 array_reverse(array, preserve);
Where array is name of the array and preserve specifies if the function should preserve the keys of the array or not. There are two possible values of preserve : true and false. It returns the reversed array.

Example :
<?php

  $my_arr = array("HTML", "CSS", "JavaScript", "PHP", "MySQL");

  $len = count($my_arr);
  for($x = 0; $x < $len; $x++) {
    echo $my_arr[$x] . ", ";
  }

  echo "<br/><br/>";

  $new_arr = array_reverse($my_arr);
  echo "After reverseing : <br/><br/>";
  $len = count($new_arr);
  for($x = 0; $x < $len; $x++) {
    echo $new_arr[$x] . ", ";
  }

?>
Output :

HTML, CSS, JavaScript, PHP, MySQL,

After reverseing :

MySQL, PHP, JavaScript, CSS, HTML,

Another example :
<?php

  $age = array("John"=> 25, "Sam" => 23, "Marry" => 30, "Luci" => 29);
 
  foreach($age as $key => $value) {
    echo $key . " : " . $value , "<br/>";
  }

  $rev_arr = array_reverse($age);

  echo "<br/> After reversing : <br/><br/>";
  foreach($rev_arr as $key => $value) {
    echo $key . " : " . $value , "<br/>";
  }

  $pre_arr = array_reverse($age, true);

  echo "<br/> After reversing (With preserve): <br/><br/>";
  foreach($pre_arr as $key => $value) {
    echo $key . " : " . $value , "<br/>";
  }

?>
Output :

John : 25
Sam : 23
Marry : 30
Luci : 29

After reversing :

Luci : 29
Marry : 30
Sam : 23
John : 25

After reversing (With preserve):

Luci : 29
Marry : 30
Sam : 23
John : 25

Next Topic :