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 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口