kphp
kphp copied to clipboard
usort() has different behavior PHP / KPHP
When compare are equal then behaviour diffrent.
<?php
class Data
{
public string $key;
public string $data;
public function __construct(string $key, string $data)
{
$this->key = $key;
$this->data=$data;
}
}
/** @var Data[] $data */
$data[] = new Data("keyA", "value1");
$data[] = new Data("keyA", "value2");
$data[] = new Data("keyB", "value3");
$data[] = new Data("keyB", "value4");
usort($data, function (Data $x, Data $y) {
return strcmp($x->key, $y->key);
});
foreach ($data as $item ){
echo "{$item->key} {$item->data}\n";
}
//check strcmp()
$rc = strcmp("keyA", "keyA");
echo sprintf("cmp: rc=%d\n", $rc);
out:
keyA value1
keyA value2
keyB value4 <<< changed
keyB value3 <<< changed
expected:
keyA value1
keyA value2
keyB value3
keyB value4