Reverse PHP array and keep keys and values

王林
Release: 2024-04-29 09:06:01
Original
1153 people have browsed it

PHP Array reverse method to preserve keys and values: (1) Use array_reverse() to reverse the array and preserve keys.

Reverse PHP array and keep keys and values

Reverse PHP array: keep keys and values

Prerequisites:

  • Have basic knowledge PHP Knowledge

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);

?>
Copy after login

Output:

array(3) {
  ["corge"]=>
  string(6) "grault"
  ["baz"]=>
  string(3) "qux"
  ["foo"]=>
  string(3) "bar"
}
Copy after login

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;
}

?>
Copy after login

Output:

ID: 3 - Name: Johnathon Doe
ID: 2 - Name: Jane Smith
ID: 1 - Name: John Doe
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template