PHP: Sort an array by the length of its values?

PHP: Sort an array by the length of its values?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Sorting Arrays by String Length in PHP

Sorting an array based on the length of its values is a straightforward task if you leverage built-in sorting functions, but it requires a specific approach because standard sort orders typically rely on the string value itself or a custom comparison logic that returns a boolean rather than a computed metric. If your goal is to order positive matches from your anagram machine so that the longest strings appear first, you need to transform the problem from "sorting by value" to "sorting by a derived property."

In PHP, the most idiomatic way to achieve this is using usort. Unlike sort or rsort, which only allow for ascending or descending orders of the raw values, usort accepts a custom comparison callback. This callback receives two arguments—let's call them $a and $b—and must return an integer: negative if $a should come before $b, positive if it should come after, and zero if they are equivalent.

To sort by length in descending order (longest first), your comparison function needs to calculate the length of both strings using strlen() and compare those integers. Here is how you would implement that:

$matches = [
    'apple',
    'pear',
    'banana',
    'kiwi'
];

usort($matches, function ($a, $b) {
    // Compare lengths in descending order
    if (strlen($b) > strlen($a)) {
        return 1;
    } elseif (strlen($b) < strlen($a)) {
        return -1;
    }
    // Lengths are equal, so we can return 0 to maintain original relative order
    // or implement a secondary sort key here if needed.
    return 0;
});

print_r($matches);
// Output: Array ( [0] => banana [1] => apple [2] => pear [3] => kiwi )

While the logic above is explicit and easy to read, it involves multiple if statements. You can condense this using the ternary operator or a shorthand comparison trick. A common pattern used in PHP communities involves swapping the operands inside the length calculation to reverse the default ascending sort behavior:

usort($matches, function ($a, $b) {
    return strlen($b) <=> strlen($a);
});

The spaceship operator (<=>) returns -1 if the left operand is less than the right, 0 if they are equal, and 1 if the left is greater. By swapping $b into the first position of the comparison (strlen($b) <=> strlen($a)), you effectively reverse the order: a longer string on the right side triggers a -1 return value (meaning the left side comes first in the final array), resulting in the longest strings appearing at the top.

This approach is efficient and readable for most scenarios. However, there is a critical edge case to consider: stability. The usort function does not guarantee a stable sort by default. If two items have the exact same length, their relative order might change between runs depending on how the underlying implementation handles equal elements. In your anagram machine context, if the string content matters as a tie-breaker (e.g., preserving the order of discovery for equal-length matches), you might need to use usort carefully or switch to a stable sorting method if available in your specific PHP version and environment.

If you are working within a Laravel project, this pattern remains consistent regardless of the framework, but understanding how to compose these sort keys is fundamental. You can extend this concept to sort by multiple criteria, such as length descending, followed by alphabetical order ascending for ties:

usort($matches, function ($a, $b) {
    $lenCompare = strlen($b) <=> strlen($a); // Descending length
    if ($lenCompare === 0) {
        return strcmp($a, $b); // Ascending alphabetical for ties
    }
    return $lenCompare;
});

This ensures that even when lengths match, the array remains predictable and deterministic. Always remember to check strlen() against empty strings or null values if your data source isn't strictly guaranteed to contain positive matches, as undefined behavior can occur with invalid types.

Our network