Home > Backend Development > PHP Tutorial > How to Preserve Key Order When Sorting Associative Arrays in PHP?

How to Preserve Key Order When Sorting Associative Arrays in PHP?

Barbara Streisand
Release: 2024-11-02 19:31:02
Original
957 people have browsed it

How to Preserve Key Order When Sorting Associative Arrays in PHP?

Preserve Key Order When Sorting Associative Arrays in PHP

Associative arrays in PHP store key-value pairs. When sorting such arrays using PHP's built-in sorting functions, it is important to consider whether or not to preserve the original key order. In this article, we will explore the current behavior of sorting in PHP and provide a custom solution for preserving key order.

PHP's Sort Functions and Stability

In PHP versions prior to 4.1.0, the sorting functions, such as asort() and uasort(), provided a stable sort. This means that when multiple keys had the same value, the order of those keys would be preserved in the sorted result. However, starting with PHP 4.1.0, stability is no longer guaranteed.

Custom Stable Sort Function

Since PHP's built-in sorting functions do not support stable sorting, we need to implement our own. The merge sort algorithm is commonly used for this purpose due to its guaranteed O(n*log(n)) time complexity:

<code class="php">function mergesort(&$array, $cmp_function = 'strcmp') {
    ...
    // Logic for splitting, merging, and sorting the array
    ...
}</code>
Copy after login

This custom function can be used with uasort() to sort the associative array while preserving the original key order:

<code class="php">uasort($arr, function($a, $b) {
    return mergesort([$a, $b]);
});</code>
Copy after login

Example Usage

<code class="php">$arr = [
    'key-1' => 10,
    'key-2' => 20,
    'key-3' => 10,
    'key-4' => 30,
];

uasort($arr, function($a, $b) {
    return mergesort([$a, $b]);
});

print_r($arr);</code>
Copy after login

Output:

Array
(
    [key-1] => 10
    [key-3] => 10
    [key-2] => 20
    [key-4] => 30
)
Copy after login

By using the custom stable sort function, the key order of the original array is preserved in the sorted output.

The above is the detailed content of How to Preserve Key Order When Sorting Associative Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template