PHP
Reverse an Associative Array While Preserving Keys
Learn how to reverse the order of elements in a PHP associative array or a numerically indexed array while keeping the original key-value associations intact using array_reverse().
<?php
$associativeArray = [
'apple' => 1,
'banana' => 2,
'cherry' => 3
];
$reversedArray = array_reverse($associativeArray, true);
print_r($reversedArray);
// Output:
// Array
// (
// [cherry] => 3
// [banana] => 2
// [apple] => 1
// )
$numericArray = [10, 20, 30, 40];
$reversedNumericArray = array_reverse($numericArray, true);
print_r($reversedNumericArray);
// Output (keys preserved):
// Array
// (
// [3] => 40
// [2] => 30
// [1] => 20
// [0] => 10
// )
How it works: The `array_reverse()` function reverses the order of elements in an array. By passing `true` as the second argument (`preserve_keys`), it ensures that the original associative keys or numeric indices are maintained, rather than re-indexing a numerically indexed array from scratch. This is crucial when you need to change element order without losing the key-value mapping.