In this tutorial, you shall learn how to sort an array of strings based on their length in PHP using usort() function, with the help of example programs.

PHP – Sort an Array of Strings based on Length

To sort an array of strings based on their length in PHP, you can use the usort() function along with a custom comparison function that compares the length of the strings.

The custom comparison function must take two strings as arguments and return if the first argument string is greater than the second argument string.

usort() function takes the string array and custom comparison function as arguments, and sorts the strings in array in place, based on the comparison function, in ascending order.

Example

In the following example, we take an array of strings, and sort the array, based on the length of strings, in ascending order.

PHP Program

<?php
$strings = array("apple", "banana", "fig", "orange", "kiwi");

function compare_length($a, $b) {
    if (strlen($a) == strlen($b)) {
        return 0;
    }
    return (strlen($a) < strlen($b)) ? -1 : 1;
}

usort($strings, "compare_length");

print_r($strings);
?>

Output

Reference to related tutorials for program

ADVERTISEMENT

Conclusion

In this PHP Tutorial, we learned how to sort an array of strings based on length, using usort() function.