Current Location: Home> Latest Articles> How to Avoid Losing Array Keys When Using PHP's asort Function? Solutions Inside

How to Avoid Losing Array Keys When Using PHP's asort Function? Solutions Inside

M66 2025-06-11

2. Common Causes of Key Loss

Although asort itself does not lose array keys, developers can easily mistake key loss under the following conditions:

  1. Using sort instead of asort:
    The sort function reindexes the array numerically (0, 1, 2...) when sorting, which results in the original keys being overwritten. If sort is mistakenly used, it leads to actual key loss.

  2. Overwriting the array and losing key association:
    For example, assigning the result of asort to another variable or directly using the return value without realizing that asort returns a boolean can cause confusion.

Incorrect usage example:

$array = ['x' => 10, 'y' => 5];  
$result = asort($array);  // $result is a boolean, not the sorted array  
print_r($result);  // You cannot print the array directly from $result  
print_r($array);   // $array is sorted in place, note that it's passed by reference  
  1. Sorting multidimensional arrays incorrectly:
    When sorting multidimensional arrays, applying asort only to the outer layer can lead to key confusion within the inner arrays.


3. How to Prevent Key Loss?

1. Confirm You Are Using asort and Not sort

$array = ['one' => 30, 'two' => 10, 'three' => 20];  
asort($array);  
print_r($array);

Ensure you are not using sort or other functions that overwrite keys.

2. Understand the Return Value of asort

asort modifies the input array directly and returns true or false, not the sorted array.

$array = ['a' => 3, 'b' => 1];  
if (asort($array)) {  
    print_r($array);  // Only here the sorted array is correctly output  
}

3. When Handling Multidimensional Arrays, Sort Each Level Separately Using asort

To sort a specific level within a multidimensional array:

$multiArray = [  
    'group1' => ['id1' => 3, 'id2' => 1],  
    'group2' => ['id3' => 5, 'id4' => 2]  
];  
foreach ($multiArray as &$subArray) {  
    asort($subArray);  
}  
unset($subArray);  // Release reference  
print_r($multiArray);

4. Practical Example: Sorting with URL Domain Replacement

Suppose you need to sort an array of URLs and replace their domain names with m66.net. Here’s how you can do it:

$array = [  
    'site1' => 'https://example.com/page1',  
    'site2' => 'http://anotherdomain.com/page2',  
    'site3' => 'https://somedomain.com/page3',  
];  
// Extract and replace the domain in each URL with m66.net  
foreach ($array as $key => $url) {  
    $parsed = parse_url($url);  
    if ($parsed && isset($parsed['host'])) {  
        $newUrl = str_replace($parsed['host'], 'm66.net', $url);  
        $array[$key] = $newUrl;  
    }  
}  
// Sort by value in ascending order while keeping the keys  
asort($array);  
print_r($array);

Output: