druhoytza979667566 2017-06-14 10:26
浏览 57
已采纳

usort差异php7.1 vs php5.6

I'm currently migrating a project from php5.6 to php7.1. Most is going well, but I just hit a wall one one test.

The function usort doesn't have the same behavior on both version, and it doesn't seem to be documented (it's not that two values are equals and then the order is undefined). In my test case, the returned array order is reversed.

Here is a reproduction of the problem. Note that I return -1 all the time for simplification (I'm focusing in the diff between PHP5.6 and 7 here)

Code run on both versions:

$a = [['value' => 1, 'toto' => 'toto'], ['value' => 1, 'toto' => null]];
usort($a, function ($a, $b) { return -1;});
print_r($a);

Results in PHP 5.6:

Array
(
    [0] => Array
        (
            [value] => 1
            [toto] =>
        )

    [1] => Array
        (
            [value] => 1
            [toto] => toto
        )

)

PHP 7.1

Array
(
    [0] => Array
        (
            [value] => 1
            [toto] => toto
        )

    [1] => Array
        (
            [value] => 1
            [toto] =>
        )

)
  • 写回答

2条回答 默认 最新

  • douganggu4392 2017-06-14 10:50
    关注

    The reason for this is that in this case the values get passed to the usort() callback in different order depending on the PHP version.

    https://3v4l.org/bW5WP

    $array = ['a', 'b'];
    usort($array, function ($firstValue, $secondValue) { echo "COMPARING: {$firstValue} with {$secondValue}
    "; return -1;});
    

    PHP 5.6 output:

    COMPARING: b with a

    PHP 7.x output:

    COMPARING: a with b

    This doesn't matter to callbacks which actually compare the given values. Your callback however always returns -1, which means first value is lesser than the second value. In PHP 5.6 this results in b being first in the list, in PHP 7.x a will be first.

    Returning incosistent results from the callback will result in undefined behavior if your callback is sorting an array of more than 2 values.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 【急】在线问答CNC雕刻机的电子电路与编程
  • ¥60 在mc68335芯片上移植ucos ii 的成功工程文件
  • ¥15 笔记本外接显示器正常,但是笔记本屏幕黑屏
  • ¥15 Python pandas
  • ¥15 蓝牙硬件,可以用哪几种方法控制手机点击和滑动
  • ¥15 生物医学数据分析。基础课程就v经常唱课程舅成牛逼
  • ¥15 云环境云开发云函数对接微信商户中的分账功能
  • ¥15 空间转录组CRAD遇到问题
  • ¥20 materialstudio计算氢键脚本问题
  • ¥15 有没有代做有偿主要做数据可视化部分即可(2023全国高考更省一本线理科类)