PHP array_reverse

Created with Sketch.

PHP array_reverse

Summary: in this tutorial, you will learn how to use the PHP array_reverse() function to reverse the order of elements in an array.

Introduction to the PHP array_reverse() function

The array_reverse() function accepts an array and returns a new array with the order of elements in the input array reversed.

The following shows the array_reverse() function:

array_reverse ( array $array , bool $preserve_keys = false ) : array

Code language: PHP (php)

The array_reverse() function has two parameters:

  • $array is the input array
  • $preserve_keys determines if the numeric keys should be preserved. If $preserve_keys is true, the numeric key of elements in the new array will be preserved. The $preserve_keys doesn’t affect the non-numeric keys.

The array_reverse() doesn’t change the input array. Instead, it returns a new array.

PHP array_reverse() function examples

Let’s take some examples of using the PHP array_reverse() function.

1) Simple PHP array_reverse() function example

The following example uses the array_reverse() function to reverse the order of an array:

<?php

$numbers = [10, 20, 30];
$reversed = array_reverse($numbers);

print_r($reversed);
print_r($numbers);

Code language: HTML, XML (xml)

Output:

Array
(
[0] => 30
[1] => 20
[2] => 10
)
Array
(
[0] => 10
[1] => 20
[2] => 30
)

Code language: plaintext (plaintext)

How it works.

  • First, define an array of three numbers 10, 20, 30.
  • Then, use the array_reverse() function to create a new array with the order of elements in the $numbers array reversed.
  • Finally, show the reversed array and the $numbers array. As you can see, the $numbers array doesn’t change.

2) Using the PHP array_reverse() function to preserve numeric keys

The following example uses the array_reverse() function to reverse elements of an array. However, it preserves the keys of the elements:

<?php

$book = [
'PHP Awesome',
999,
['Programming', 'Web development'],
];

$preserved = array_reverse($book, true);

print_r($preserved);

Code language: HTML, XML (xml)

Output:

Array
(
[2] => Array
(
[0] => Programming
[1] => Web development
)

[1] => 999
[0] => PHP Awesome
)

Code language: PHP (php)

Summary

  • Use the PHP array_reverse() function to reverse the order of elements in an array.
  • Set the $preserve_keys to true to preserve the keys in the original array.

Leave a Reply

Your email address will not be published. Required fields are marked *