PHP: Sort words by length

Sort with a custom rule: first by length, then in alphabetical order.

What to build

A program that sorts words by their length.

Requirements

  • Read one line of words separated by single spaces.
  • Print the words sorted by length (short first); words of the same length are sorted alphabetically (with strcmp). Separate them by spaces.

Input

One line of words.

Output

One line.

Constraints

1 to 50 lower-case words.

Example

Input:

the quick brown fox jumps over the lazy dog

Output:

dog fox the the lazy over brown jumps quick

Why it works

The callback returns a negative, zero or positive number, and ?: falls back to the second rule only on a tie.

Examples

Example 1 · Input
the quick brown fox jumps over the lazy dog
Expected output
dog fox the the lazy over brown jumps quick
Example 2 · Input
banana apple cherry fig
Expected output
fig apple banana cherry

Hints

Hint 1

usort($words, fn($a, $b) => ...) sorts with your own rule.

Hint 2

strlen($a) <=> strlen($b) ?: strcmp($a, $b) uses the text when the lengths are equal.

Solution

Show one correct solution (try it yourself first)
<?php
$words = explode(" ", trim(fgets(STDIN)));
usort($words, fn($a, $b) => strlen($a) <=> strlen($b) ?: strcmp($a, $b));
echo implode(" ", $words), "\n";

▶ Open this solution in the compiler

Lesson: String and array functions →