PHP
Reverse the Order of Elements in an Array
Learn to easily reverse the order of elements in any PHP array, whether indexed or associative, using the array_reverse function while optionally preserving keys.
<?php
$indexedArray = ['first', 'second', 'third', 'fourth'];
// Reverse without preserving keys (default behavior)
$reversedIndexed = array_reverse($indexedArray);
print_r($reversedIndexed);
$associativeArray = [
'a' => 1,
'b' => 2,
'c' => 3
];
// Reverse and preserve keys
$reversedAssociative = array_reverse($associativeArray, true);
print_r($reversedAssociative);
How it works: This snippet demonstrates `array_reverse()`, a straightforward PHP function that reverses the order of elements in an array. It can be used for both indexed and associative arrays. The second optional boolean argument, when set to `true`, tells the function to preserve the original keys, which is crucial for maintaining relationships in associative arrays.