PHP array_reverse() Function (original) (raw)

Skip to content

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 <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>a</mi><mi>r</mi><mi>r</mi><mi>a</mi><mi>y</mi><mo separator="true">,</mo><mi>b</mi><mi>o</mi><mi>o</mi><mi>l</mi></mrow><annotation encoding="application/x-tex">array , bool </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">rr</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.03588em;">y</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">b</span><span class="mord mathnormal">oo</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span></span></span></span>preserve_keys = false ) : arrayCode language: PHP (php)

The array_reverse() function has two parameters:

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

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

`<?php

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

print_r($reversed); print_r($numbers);`Code language: HTML, XML (xml)

Try it

Output:

Array ( [0] => 30 [1] => 20 [2] => 10 ) Array ( [0] => 10 [1] => 20 [2] => 30 )Code language: plaintext (plaintext)

How it works.

Preserving 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=arrayreverse(preserved = array_reverse(preserved=arrayreverse(book, true);

print_r($preserved);`Code language: HTML, XML (xml)

Try it

Output:

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

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

)`Code language: PHP (php)

Summary #

Did you find this tutorial useful?