PHP Program to Reverse Array with Example Output
array_reverse($array), which returns a new array with elements in reverse order.Examples
How to Think About It
Algorithm
Code
<?php // Original array $array = [1, 2, 3, 4, 5]; // Reverse the array using built-in function $reversed = array_reverse($array); // Print the reversed array print_r($reversed); ?>
Dry Run
Let's trace the example array [1, 2, 3, 4, 5] through the code.
Original array
The array is [1, 2, 3, 4, 5].
Call array_reverse
The function processes elements starting from 5 to 1.
Create reversed array
New array becomes [5, 4, 3, 2, 1].
Print reversed array
Output shows the reversed array.
| Index | Original Value | Reversed Index | Reversed Value |
|---|---|---|---|
| 0 | 1 | 4 | 5 |
| 1 | 2 | 3 | 4 |
| 2 | 3 | 2 | 3 |
| 3 | 4 | 1 | 2 |
| 4 | 5 | 0 | 1 |
Why This Works
Step 1: Using array_reverse
The array_reverse function takes the original array and returns a new array with elements in reverse order.
Step 2: No change to original array
The original array stays the same; the reversed array is a new copy.
Step 3: Printing the array
Using print_r shows the reversed array in a readable format.
Alternative Approaches
<?php $array = [1, 2, 3, 4, 5]; $reversed = []; for ($i = count($array) - 1; $i >= 0; $i--) { $reversed[] = $array[$i]; } print_r($reversed); ?>
<?php $array = [1, 2, 3, 4, 5]; $length = count($array); for ($i = 0; $i < $length / 2; $i++) { $temp = $array[$i]; $array[$i] = $array[$length - 1 - $i]; $array[$length - 1 - $i] = $temp; } print_r($array); ?>
Complexity: O(n) time, O(n) space
Time Complexity
Reversing an array requires visiting each element once, so the time is proportional to the number of elements, O(n).
Space Complexity
Using array_reverse creates a new array, so it uses O(n) extra space. The in-place swap method uses O(1) space.
Which Approach is Fastest?
The built-in array_reverse is optimized and easy to use, but in-place reversal saves memory at the cost of more complex code.
| Approach | Time | Space | Best For |
|---|---|---|---|
| array_reverse() | O(n) | O(n) | Simplicity and readability |
| Manual loop reversal | O(n) | O(n) | Learning how reversal works |
| In-place swap reversal | O(n) | O(1) | Memory efficiency |
array_reverse for a quick and easy way to reverse arrays in PHP.