PHP Reverse Array

PHP Reverse Array is used to Return an array with elements in reverse order. Reverse Array accepts two parameters, first parameter is the array and it is mandatory. Second parameter is preserve keys, If set to TRUE numeric keys are preserved. Non-numeric keys are not affected by this setting and will always be preserved. And second parameter it’s not mandatory. Here is a simple example for Reverse Array.

Syntax of PHP Reverse Array

This is the syntax of PHP Reverse Array. $array is the array to reverse order. $preserve_keys is a boolean value, If it’s set to TRUE numeric keys are preserved. Non-numeric keys are not affected by this setting and will always be preserved.

array_reverse ( $array, bool $preserve_keys )
1

Example code for PHP Reverse Array

<?php
$colour=array("red","green","blue","yellow");
$reverse=array_reverse($colour);

echo "<pre>";
print_r($colour);
print_r($reverse);
echo "</pre>";
?>

Original array output will be

Reverse array output will be

Above same code with preserved array

Everything is same as above array, only using preserved array to be true

<?php
$colour=array("red","green","blue","yellow");
$preserve=array_reverse($colour,true);

echo "<pre>";
print_r($preserve);
echo "</pre>";
?>

Output of preserved array will be

2

Code for PHP Reverse Array with two dimensional array

This is same array as above, here it is a multidimensional array.

$colour1=array("red","green",array("blue","yellow"));
$reverse=array_reverse($colour1);
$preserve=array_reverse($colour1,true);

echo "<pre>";
print_r($colour1);
print_r($reverse);
print_r($preserve);
echo "</pre>";
?>

Output of original array will be

Output of reverse array will be

And preserved array output will be

If you have any problem while using array reverse, let me know using comment form below.

Vivek Vengala
 

Vivek Vengala is a Online Entrepreneur, Web Developer from Hyderabad India.

Click Here to Leave a Comment Below 0 comments

Leave a Reply:

x

Join My Facebook Group to Receive Coding Tutorial for Free

email-subsribe