1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【PHP】PHP5でusortの比較結果が等しくなる要素の時に配列の並び順が変わってしまう

Last updated at Posted at 2022-03-11

結論

usortの比較結果が等しくなる時(callbackが0を返す時)は配列の順番は変わらないと思っていたがPHP5ではそれが変わってしまう。
※公式ではPHP8.0.0より前のバージョンで起こるとのこと。

試したこと

検証コード

$vals = ['first', 'second', 'third'];

usort($vals, function($a, $b) {
   return 0; 
});

print_r($vals);

期待した出力

Array
(
    [0] => first
    [1] => second
    [2] => third
)

実際の出力

Array
(
    [0] => third
    [1] => second
    [2] => first
)

PHPのどのバージョンから並び順が変わるかを確認した

3V4Lを使って各バージョンの挙動を確認した。
Screen Shot 2022-03-11 at 19.52.16.png
php5では並び順が変わってしまうらしい。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?