Does returning “-1” with usort really move the $b variable or does it keep it in the same place?

允我心安 提交于 2019-12-11 14:16:38

问题


A simple piece of code written by me:

<?php
function testing($a,$b){
    if ($a < $b ){
        return -1;
    }
    elseif ($a > $b){
        return 1;
    }
    //else {
        //return 0;
    //}
}

$array = array(1,3,2,4,5);
usort($array, "testing");
var_dump($array);
?>

This is from the top comment (highest rated comment and from 5 years ago) on the php.net manual's usort page:

"If you return -1 that moves the $b variable down the array, return 1 moves $b up the array and return 0 keeps $b in the same place."

As far as I was looking at the piece of code that I've written returning "-1" does not move the $b, it stays in the same place. It is only the "return 1;" statement that moves the $b (as compared to the $a, current $a-$b) pair.

Lets say we have something like this: [1,3],2,4,5 - Return -1

The square brackets indicate the current $a-$b pair. Would we get something like this: 1,2,3,4,5 ,meaning the $b would be switched with the following element which is out of the current $a-$b pair? The point here is that I think that it is only the current $a-$b elements that can get switched. And with this the "return -1;" statement does not do any moving, which is not how I was thinking this works.

来源:https://stackoverflow.com/questions/46547848/does-returning-1-with-usort-really-move-the-b-variable-or-does-it-keep-it-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!