PHP array_reverse() Function

What is PHP array_reverse() Function?

If you want to reverse the order of all the elements of an array, use PHP array_reverse() function.

Syntax:

array_reverse(array, preserve_key)

Parameters:

The Function has 1 required parameter and 1 optional parameter –

array (Required): The input array.

preserve_key (Optional): It is a boolean value. For the array of numeric keys, you can set whether you want to preserve the keys in the resulting array-

  • Set TRUE or 1, if you want to preserve the original elements’ numeric keys. Check example 2.
  • Set FALSE or 0, if you don’t want to preserve the original elements’ numeric key. It is the default value, so, if you don’t mention this parameter, in the resulting array the original keys are not preserved. Check example 3.

Non-numeric keys (or associative keys) are always preserved. Check example 4.

Return Values:

The function returned the reversed array. Check example 1.

Examples:

Example 1:

<pre>
<?php
$original_arr = ["Zero", "One", "Two", "Three"];
$reversed_arr = array_reverse($original_arr);
echo "After reversing, the array is : ";
print_r($reversed_arr);
?>
</pre>

Output:

After reversing, the array is: Array
(
[0] => Three
[1] => Two
[2] => One
[3] => Zero
)

Example 2:

<pre>
<?php
$original_arr = ["Zero", "One", "Two", "Three"];
$reversed_arr = array_reverse($original_arr, TRUE);
echo "After reversing, the array is: ";
print_r($reversed_arr);
?>
</pre>

Output:

After reversing, the array is: Array
(
[3] => Three
[2] => Two
[1] => One
[0] => Zero
)

Example 3:

<pre>
<?php
$original_arr = ["Zero", "One", "Two", "Three"];
$reversed_arr = array_reverse($original_arr, FALSE);
echo "After reversing, the array is : ";
print_r($reversed_arr);
?>
</pre>

Output:

After reversing, the array is : Array
(
[0] => Three
[1] => Two
[2] => One
[3] => Zero
)

Example 4:

<pre>
<?php
$original_arr = ["One" => 1, "Two" => 2, "Three" => 3, "Zero" => 0];
$reversed_arr = array_reverse($original_arr, TRUE);
echo "After reversing, the array is: ";
print_r($reversed_arr);
?>
</pre>

Output:

After reversing, the array is: Array
(
[Zero] => 0
[Three] => 3
[Two] => 2
[One] => 1
)




Notes on array_reverse() Function:

The function doesn’t modify the original array.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP array_reverse() Function

The array_reverse() function is a built-in PHP function and part of the PHP’s array functions. It is a useful and quick way to reverse element order of an array.

Reference:

https://www.php.net/manual/en/function.array-reverse.php