11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHP7調査(12)<=>演算子の新設

Last updated at Posted at 2015-04-11

PHP7から<=>という2項演算子が導入されます。他の言語では宇宙船演算子などと呼ばれることもありますね。

これは2値を==で比較して、等しければ0を、左の方が大きければ正値を、右の方が大きければ負値を返すような演算子です。strcmp()の==版だと考えるのが手っ取り早いでしょう。

この演算子を使えば、usort()に渡すソート関数が簡単に書けるようになります。RFCに載っているサンプルを紹介します。

<?php
if (($handle = fopen("people.csv", "r")) !== FALSE) {
    while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
         $data[] = $row;
    }
    fclose($handle);
}
 
// Sort by last name:
usort($data, function ($left, $right) {
     return $left[1] <=> $right[1];
});

参照

11
10
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
11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?