PHP

Reverse the Order of Array Elements

Quickly reverse the order of elements in any PHP array, with an option to preserve the original keys or re-index the array for a new sequence.

<?php
// Simple indexed array
$numbers = [10, 20, 30, 40, 50];
echo "Original Indexed Array: ";
print_r($numbers);

// Reverse without preserving keys (default behavior, re-indexes numerically)
$reversedNumbers = array_reverse($numbers);
echo "Reversed Indexed Array (keys re-indexed): ";
print_r($reversedNumbers);
/* Output:
Original Indexed Array: Array ( [0] => 10 [1] => 20 [2] => 30 [3] => 40 [4] => 50 )
Reversed Indexed Array (keys re-indexed): Array ( [0] => 50 [1] => 40 [2] => 30 [3] => 20 [4] => 10 )
*/

// Associative array
$data = [
    'name' => 'Alice',
    'age' => 30,
    'city' => 'New York'
];
echo "Original Associative Array: ";
print_r($data);

// Reverse and preserve keys
$reversedData = array_reverse($data, true);
echo "Reversed Associative Array (keys preserved): ";
print_r($reversedData);
/* Output:
Original Associative Array: Array ( [name] => Alice [age] => 30 [city] => New York )
Reversed Associative Array (keys preserved): Array ( [city] => New York [age] => 30 [name] => Alice )
*/
How it works: This snippet demonstrates `array_reverse()`, a straightforward PHP function to reverse the order of elements in an array. It takes an optional second parameter, `preserve_keys`, which, when set to `true`, ensures that the original associative keys are maintained. If `false` (the default), numerical keys are re-indexed. This function is valuable for presenting data in reverse chronological order, stack-like operations, or processing elements from the end of a list.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs