Spaceship operator confusion in PHP7 (return -1)
我对PHP7还很陌生,到目前为止,它看起来很强大。我一直在使用php5.6,所以我开始了解宇宙飞船操作员
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | Function normal_sort($a, $b) : int { if( $a == $b ) return 0; if( $a < $b ) return -1; return 1; } function space_sort($a, $b) : int { return $a <=> $b; } $normalArray = [1,34,56,67,98,45]; //Sort the array in asc usort($normalArray, 'normal_sort'); foreach($normalArray as $k => $v) { echo $k.' => '.$v.''; } $spaceArray = [1,34,56,67,98,45]; //Sort it by spaceship operator usort($spaceArray, 'space_sort'); foreach($spaceArray as $key => $value) { echo $key.' => '.$value.''; } |
当你有三possibilities价值,是通过比较两大功能:一个比较
从usort(手册)
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
-
$a < $b -1 回报 -
$a == $b 0 回报 -
$a > $b 1 回报
这是不是如何在PHP类型的工作,但你可以认为它是