Home > Article > Backend Development > Reverse PHP array and keep keys and values
PHP Array reverse method to preserve keys and values: (1) Use array_reverse() to reverse the array and preserve keys.

Prerequisites:
Code Example:
There are various ways to reverse a PHP array while preserving the keys and values. The following is one of the most commonly used methods:
<?php
$originalArray = [
'foo' => 'bar',
'baz' => 'qux',
'corge' => 'grault'
];
// 使用 array_reverse() 反转数组
$reversedArray = array_reverse($originalArray, true);
// 输出反转后的数组
var_dump($reversedArray);
?>Output:
array(3) {
["corge"]=>
string(6) "grault"
["baz"]=>
string(3) "qux"
["foo"]=>
string(3) "bar"
}Practical example:
Suppose you have a An array containing information about users that you want to display in reverse order. You can use array_reverse() to achieve this conveniently:
<?php
$users = [
['id' => 1, 'name' => 'John Doe'],
['id' => 2, 'name' => 'Jane Smith'],
['id' => 3, 'name' => 'Johnathon Doe']
];
// 反转数组
$reversedUsers = array_reverse($users, true);
// 循环输出反转后的用户
foreach ($reversedUsers as $user) {
echo "ID: {$user['id']} - Name: {$user['name']}" . PHP_EOL;
}
?>Output:
ID: 3 - Name: Johnathon Doe ID: 2 - Name: Jane Smith ID: 1 - Name: John Doe
The above is the detailed content of Reverse PHP array and keep keys and values. For more information, please follow other related articles on the PHP Chinese website!