'Spaceship' Operator <=> in PHP 7

The PHP development team already announced the new version of PHP 7.0.0 RC 5. It comes with many more new features, and I'm excited about one of the feature called Spaceship Operator <=>.
Those who already knows PERL or RUBY programming basics may be familiar with this new operator too.

What is it or How does it work?

It's actually called Combined Comparison Operator in short spaceship operator.

Basically it works in three ways,

  • Returns 0 if values of both sides are the same.
  • Returns -1 if the value of right side is greater than the left side.
  • Returns 1 if the value of left side is greater than the right side.

Here is some codes for examples,

// Numbers
echo 6 <=> 6; // 0
echo 16 <=> 25; // -1
echo 6.5 <=> 10.7; // 1

// Strings
echo "e" <=> "e"; // 0
echo "a" <=> "c"; // -1
echo "r" <=> "a"; // 1

Let's check another example on usort,

// Access data from csv file
if (($handle = fopen("user_info.csv", "r")) !== FALSE) {
    while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
        //placing single row as an array element
        $information[] = $row;
    }
    fclose($handle);
}


// Single array element will be looks like, 
//  [
//  "first_name" => "Ashraful",
//  "last_name" => "Islam",
//   ]
//
// Sort by last name:
usort($information, function ($leftSide, $rightSide) {
    return $leftSide[1] <=> $rightSide[1];
});

For more information you can look into official php documentations.

comments powered by Disqus