Home > Net >  Upgrade to PHP 8.2: ksort and krsort changes
Upgrade to PHP 8.2: ksort and krsort changes

Time:12-24

I am preparing upgrade to PHP 8.2 on a big application, and obviously going through changes between PHP 8.1 and 8.2. One of the BC breaking changes mentioned HERE is:

ksort() and krsort() now do numeric string comparison under SORT_REGULAR using the standard PHP 8 rules now.

I don't seem to understand what this means. Since ksort sorts by keys, I assumed BEFORE it would NOT sort something like this:

[
    '-5' => 'minus five',
    '4' => 'THIS SHOULD MOVE',
    '1' => 'one',
    '2' => 'two',
    '100' => 'hundred',
];
ksort($arr, SORT_REGULAR);
var_dump($arr);

But I used https://onlinephp.io/ and the it works just fine on 7.x, 8.1 and 8.2. I tried with SORT_REGULAR and without.

array(5) {
  [-5]=>
  string(10) "minus five"
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [4]=>
  string(16) "THIS SHOULD MOVE"
  [100]=>
  string(7) "hundred"
}

Can someone explain to me what am I not understanding here?

CodePudding user response:

This seems to be more about mixing alpha and numeric keys, so in your example this isn't an issue.

If you change the array to be

$arr = [
    '-5' => 'minus five',
    'a' => 'THIS SHOULD MOVE',
    '1' => 'one',
    '100' => 'hundred',
    '2' => 'two',
];

prior to 8.2, this gives (tested with Result for 8.1.13, 8.0.26, 7.4.33: on https://onlinephp.io/)

array(5) {
  [-5]=>
  string(10) "minus five"
  ["a"]=>
  string(16) "THIS SHOULD MOVE"
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [100]=>
  string(7) "hundred"
}

with the alpha being between the -ve and placed prior to the ve numbers.

With 8.2, this instead will output

array(5) {
  [-5]=>
  string(10) "minus five"
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [100]=>
  string(7) "hundred"
  ["a"]=>
  string(16) "THIS SHOULD MOVE"
}

The article at PHP 8.2: ksort(..., SORT_REGULAR) sort order changes goes into this more with...

Prior to PHP 8.2, ksort it placed alphabetical keys prior to numeric keys. For example, when sorting an array with a, b, 1, and 2 as keys, the sorted order would be a, b, 1, 2 because alphabetical keys are placed prior to numeric keys. Since PHP 8.2, ksort function is made consistent with the other array sort functions, and places numeric keys prior to alphabetical keys.

  • Related