Home > Article > Backend Development > How to Sort a PHP Array by String Length in Descending Order?
In the realm of anagram-matching, arranging positive matches in descending order of their lengths can be a crucial step. If you're facing this challenge in PHP, here's a solution using the powerful usort function.
<code class="php">function sortByLength($a, $b) { return strlen($b) - strlen($a); } usort($array, 'sortByLength');</code>
This custom sortByLength function compares the lengths of two strings and returns a negative value if the first string is longer. The usort function sorts the array in place using the comparison function provided.
Alternatively, if you need to preserve the original array indexes, you can use uasort instead:
<code class="php">uasort($array, 'sortByLength');</code>
While both usort and uasort offer viable solutions, usort is considered an unstable sort, which means that equal elements may not maintain their original order after sorting. Therefore, the version provided ensures a stable sorting behavior.
To illustrate the sorting process, consider the following array:
<code class="php">$array = ["bbbbb", "dog", "cat", "aaa", "aaaa"];</code>
After sorting, the array will be arranged as follows:
[0] => "bbbbb" [1] => "aaaa" [2] => "aaa" [3] => "cat" [4] => "dog"
The above is the detailed content of How to Sort a PHP Array by String Length in Descending Order?. For more information, please follow other related articles on the PHP Chinese website!