Friday, December 12, 2025
HomeLanguagesPHP 7 | Spaceship Operator

PHP 7 | Spaceship Operator


This article will make you aware of a very useful operator i.e the spaceship operator PHP 7. The spaceship operator or combined comparison operator is denoted by “<=>“. This is a three-way comparison operator and it can perform greater than, less than and equal comparison between two operands.
This operator has similar behavior like strcmp() or version_compare(). This operator can be used with integers, floats, strings, arrays, objects, etc.
This <=> operator offers combined comparison :

  • Return 0 if values on either side are equal
  • Return 1 if value on the left is greater
  • Return -1 if the value on the right is greater

Example:

 // Comparing Integers

echo 1 <=> 1; // outputs 0
echo 3 <=> 4; // outputs -1
echo 4 <=> 3; // outputs 1

// String Comparison

echo "a" <=> "a"; // outputs 0 
echo "m" <=> "y"; // outputs -1
echo "y" <=> "c"; // outputs 1




<?php
echo"Integers \n";
echo 7 <=> 7 ;
echo"\n";
echo 7 <=> 6;
echo"\n";
echo 6 <=> 7;
  
echo"\nFloat\n";
  
echo 2.5 <=> 1.5; 
echo"\n";
echo 0.5 <=> 1.5; 
echo"\n";
echo 1.5 <=> 1.5; 
  
echo"\nStrings\n";
echo "a" <=> "a" ;
echo"\n";
echo "g" <=> "b"
echo"\n";
echo "a" <=> "b"
  
echo"\nArrays\n";
echo [] <=> []; 
echo"\n";
echo [1, 7, 3] <=> [1, 7, 3];
echo"\n";
echo [1, 7, 3, 5] <=> [1, 7, 3];
echo"\n";
echo [1, 7, 3] <=> [4, 4, 4];
echo"\n";
  
  
?>


Output:

Integers 
0
1
-1
Float
1
-1
0
Strings
0
1
-1
Arrays
0
0
1
-1

Reference:http://php.net/manual/en/language.operators.comparison.php

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32445 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6813 POSTS0 COMMENTS
Nicole Veronica
11952 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12029 POSTS0 COMMENTS
Shaida Kate Naidoo
6949 POSTS0 COMMENTS
Ted Musemwa
7199 POSTS0 COMMENTS
Thapelo Manthata
6894 POSTS0 COMMENTS
Umr Jansen
6881 POSTS0 COMMENTS