Sorting With Minus

<?php

$array = ['a' => 1, 'b' => 2, 0, 'f' => 4, '-f' => 5];
ksort($array);

/**
Array
(
    [-f] => 5
    [0] => 0
    [a] => 1
    [b] => 2
    [f] => 4
)
*/

?>

Did you know that sorting f, 0 and -f actually ends up with -f first, then 0, then f. And this works with any string, including strings with duplicate initial minus signs.

This is the SORT_REGULAR, with which PHP compares normally different pieces of data. Any string whose first character has an ASCII code lower than 0 will be sorted first (in PHP 8.2+) : this means characters up to /. Then any starting character beyond 9, aka colon : and beyond, are sorted after the 0 (and any digit).

That normal sort is used in ksort() and krsort() since PHP 8.2. This means that these functions may behave differently, when the keys string start with a - since.

This sort will sort string starting with - first: given the ASCII table, it also will sort strings starting with + before the -. Use this feature with caution.

See Also

PHP Features

Last updated: 14 July 2026