How to Reverse Arrays in PHP Using array_reverse

This guide explains the PHP array_reverse function, its parameters, and provides step‑by‑step code examples showing how to reverse both indexed and associative arrays, including preserving keys when needed.

php Courses
php Courses
php Courses
How to Reverse Arrays in PHP Using array_reverse

PHP is a powerful scripting language not only for web development but also for array manipulation. This article introduces the PHP function array_reverse for reversing the order of array elements.

Function Syntax

The syntax of array_reverse is:

array array_reverse ( array $array [, bool $preserve_keys = FALSE ] )

Parameters: $array: The array to be reversed. $preserve_keys: When FALSE (default), keys are reindexed; when TRUE, original keys are preserved.

Basic Example

The following code demonstrates reversing a simple indexed array:

<?php
// Create a simple array
$fruits = array("apple", "banana", "orange", "grape");

// Output original array
echo "Original array:";
print_r($fruits);

// Reverse the array
$reversed_fruits = array_reverse($fruits);

// Output reversed array
echo "Reversed array:";
print_r($reversed_fruits);
?>

Running this script produces:

Original array: Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => grape
)
Reversed array: Array
(
    [0] => grape
    [1] => orange
    [2] => banana
    [3] => apple
)

The output shows that the elements have been successfully reversed.

Preserving Keys

If you need to keep the original keys after reversal, pass true as the second argument:

$reversed_fruits = array_reverse($fruits, true);

This technique works for both simple indexed arrays and associative arrays.

Overall, the array_reverse function provides a straightforward way to invert array order in PHP, with an optional flag to retain original keys.

backendcoding tutorialarray manipulationarray_reverse
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.