Topbar widget area empty.
  • Home  /
  • PHP   /
  • Spaceship Operator – PHP 7
Spaceship Operator – PHP 7 Spaceship Operator – PHP 7 - Spaceship Operator – PHP 7 Full view

Spaceship Operator – PHP 7

Spaceship Operator – PHP 7

The Spaceship Operator also known as Combined Comparison (<=>)  introduced in PHP 7 is used for comparing two expressions, and it returns -1 if the left side is smaller, 0 if the values are equal and 1 if the left side is larger.

Examples:

<?php
 //Integer Comparison
 echo 1 <=> 2; // returns -1
 echo 5 <=> 5; // returns 0 
 echo 2 <=> 1; // returns 1
 
 //String Comparison
 echo "x" <=> "y"; // returns -1
 echo "x" <=> "x"; // returns 0 
 echo "y" <=> "x"; // returns 1
 
 //Array Comparison
 echo [1, 2, 3] <=> [1, 2, 4]; // returns -1
 echo [] <=> []; // returns 0
 echo [1, 2, 3] <=> [1, 2, 3]; // returns 0
 echo [1, 2, 3] <=> []; // returns 1
 echo [1, 2, 3] <=> [1, 2, 1]; // returns 1 
 echo 5 <=> 5; // returns 0
 echo 3 <=> 2; // returns 1
?>

Similarly it can be used for floats, and objects as well.

Written by admin

Related Articles

Leave a comment