How to Sort a PHP Array by String Length in Descending Order?

Linda Hamilton
Release: 2024-11-01 04:44:27
Original
188 people have browsed it

How to Sort a PHP Array by String Length in Descending Order?

Sorting an Array by Value Length in PHP

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>
Copy after login

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>
Copy after login

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>
Copy after login

After sorting, the array will be arranged as follows:

[0] => "bbbbb"
[1] => "aaaa"
[2] => "aaa"
[3] => "cat"
[4] => "dog"
Copy after login

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!

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