Although asort itself does not lose array keys, developers can easily mistake key loss under the following conditions:
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.
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
Sorting multidimensional arrays incorrectly:
When sorting multidimensional arrays, applying asort only to the outer layer can lead to key confusion within the inner arrays.
$array = ['one' => 30, 'two' => 10, 'three' => 20];
asort($array);
print_r($array);
Ensure you are not using sort or other functions that overwrite keys.
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
}
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);
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: