LoginSignup
17
9

More than 5 years have passed since last update.

PHP7の宇宙船演算子 <=> 並みにPHP5で短く書く方法

Last updated at Posted at 2017-06-26
PHP7
$a <=> $b
PHP5(読みやすいが比較回数が常に2回)
($a > $b) - ($a < $b)
PHP5(やや読みにくいが比較回数が1回になる場合もある)
+($a > $b) ?: -($a < $b)

整数キャストで true → 1,false → 0 と変換されることを利用している

function compare($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return $a < $b ? -1 : 1;
}

↑こんなの書かなくてええんやで!


ちなみに中身が整数に限定されるときはこれだけで十分です

$a - $b

浮動小数点数とか文字列とか入ってるとアウト

17
9
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
17
9