Sunday, November 17, 2024
Google search engine
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 Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments