← Back to all snippets
PHP

Reverse a PHP Array While Preserving Keys

Learn how to reverse the order of elements in a PHP array, including associative arrays, without losing their original key-value relationships using `array_reverse()`.

<?php
$associativeArray = ['a' => 1, 'b' => 2, 'c' => 3];
$reversedAssociative = array_reverse($associativeArray, true);
echo "Reversed Associative (keys preserved):
";
print_r($reversedAssociative);

$indexedArray = [10, 20, 30];
$reversedIndexed = array_reverse($indexedArray, true); // Preserves integer keys
echo "
Reversed Indexed (keys preserved):
";
print_r($reversedIndexed);

$reversedIndexedNoKeyPreserve = array_reverse($indexedArray, false); // Re-indexes numeric keys
echo "
Reversed Indexed (keys re-indexed):
";
print_r($reversedIndexedNoKeyPreserve);
?>
How it works: The `array_reverse()` function returns an array with elements in reverse order. By setting the second optional parameter `preserve_keys` to `true`, both string and integer keys are preserved. If set to `false` (default), integer keys are re-indexed numerically, while string keys remain unchanged, making it crucial for maintaining specific array structures.

Need help integrating this into your project?

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

Hire DigitalCodeLabs