PHP
Reverse the Order of Elements in a PHP Array
Learn how to quickly reverse the order of elements in both indexed and associative PHP arrays, maintaining or discarding keys as needed with `array_reverse()`.
<?php
$indexedArray = ['apple', 'banana', 'cherry'];
$reversedIndexed = array_reverse($indexedArray);
echo "Original Indexed Array: " . implode(', ', $indexedArray) . "
";
echo "Reversed Indexed Array (keys reset): " . implode(', ', $reversedIndexed) . "
";
$associativeArray = [
'a' => 'apple',
'b' => 'banana',
'c' => 'cherry'
];
$reversedAssociativeKeysPreserved = array_reverse($associativeArray, true);
$reversedAssociativeKeysReset = array_reverse($associativeArray, false);
echo "Original Associative Array: ";
print_r($associativeArray);
echo "Reversed Associative Array (keys preserved): ";
print_r($reversedAssociativeKeysPreserved);
echo "Reversed Associative Array (keys reset): ";
print_r($reversedAssociativeKeysReset);
?>
How it works: The `array_reverse()` function in PHP reverses the order of elements in an array. By default, it re-indexes numerically indexed arrays and does not preserve keys in associative arrays. However, passing `true` as the second argument to `array_reverse()` ensures that the keys are preserved in an associative array, allowing for flexible control over the output structure.