Most of the other answers here are focused around how to fix the problem, but I thought I'd try and explain why this changed in PHP 8, which I think is what you're interested in.
PHP 8 introduced the Stable Sorting RFC, which (as it sounds) means that all sorting functions in PHP are now "stable". More details about this in the link.
The other answers covered this well already, but your function returns either zero or a number greater than zero. Previous implementations of sorting in PHP (in all versions lower than 8) considered zero and a negative number the same; as the RFC above mentions, the check was simply for a number greater than zero, or not. Returning zero would mean that these elements were treated the same as the case where $a < $b
.
PHP introduced a deprecation warning so that a lot of sorting implementations that return booleans would still work. The RFC gives some more details on this, but importantly it means PHP 8 is still backwards compatible with them (hence this being a deprecation notice, rather than a warning). The edge-case here is that while your function effectively returns a boolean - 0 for the same length, and 1 for the case where $a < $b
- because you cast this to an integer, the backwards-compatibility check in PHP 8 does not catch it, and so all "equal" elements are considered as though $a < $b
Compare:
function($a, $b) { return (int) (strlen($a) < strlen($b)); }
As in the question - works correctly in PHP <8, but raises no deprecation notice. https://3v4l.org/MP2IF
function($a, $b) { return strlen($a) < strlen($b); }
Returns a boolean, so the backwards-compatibility check in PHP 8 works correctly. But a deprecation notice is now raised. https://3v4l.org/fWR2Y
function($a, $b) { return strlen($b) <=> strlen($a); }
The "correct" solution, working correctly in all versions (at least since the spaceship operator was introduced). https://3v4l.org/6XRYW
because you cast this to an integer, the backwards-compatibility check in PHP 8 does not catch it
- funnily enough, i cast it to integer to get rid of the warning in some old PHP5-7 code I was updating to PHP8 xD – Vituperation