← Back to all snippets
PHP

Reversing an Array While Preserving Original Keys

Learn how to reverse the order of elements in a PHP array, including both sequential and associative arrays, while optionally preserving the original key-value associations.

<?php
$sequentialArray = ['a', 'b', 'c', 'd'];
$associativeArray = ['key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'];

// Reverse without preserving keys (default for sequential arrays)
$reversedSequential = array_reverse($sequentialArray);
echo "Reversed Sequential (keys reset):
";
print_r($reversedSequential);

// Reverse and preserve keys for associative array
$reversedAssociativePreserveKeys = array_reverse($associativeArray, true);
echo "
Reversed Associative (keys preserved):
";
print_r($reversedAssociativePreserveKeys);

// Reverse sequential array and preserve numeric keys
$reversedSequentialPreserveKeys = array_reverse($sequentialArray, true);
echo "
Reversed Sequential (numeric keys preserved):
";
print_r($reversedSequentialPreserveKeys);
?>
How it works: The array_reverse() function returns an array with the elements in reverse order. By default, for numerically indexed arrays, it re-indexes the array (keys are reset to 0, 1, 2...). However, when the second argument (`preserve_keys`) is set to `true`, the function will maintain the original key-value associations, which is crucial for associative arrays or when specific numeric keys hold significance, preventing data loss or unexpected reordering.

Need help integrating this into your project?

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

Hire DigitalCodeLabs