Back to questions
JuniorTheoryCommon
What does the program print?
<?php
$words = ['pear', 'fig', 'banana'];
usort($words, fn($a, $b) => strlen($a) <=> strlen($b));
echo implode(' ', $words), "\n";fig pear banana
- Expecting
usortto return a sorted copy and leave$wordsalone: it receives the array by reference, sorts it in place and returnstrue. - Expecting
$a <=> $bto sort from largest to smallest: it is negative when$ais smaller, which puts$afirst; descending needs$b <=> $a.
- How would you change the comparison function to sort the words from longest to shortest?
- What would
$sorted = usort($words, …)put into$sorted?