PHP 7 Spaceship Operator: Use, Syntax, and Examples

By IncludeHelp Last updated : January 20, 2024

PHP 7 Spaceship Operator

The PHP spaceship operator is used to compare two expressions. It is a binary kind of operator that requires two operands (let's suppose $x and $y). It returns -1, 0, or 1 when $x is respectively less than, equal to, or greater than $y.

Note

The spaceship operator is added in PHP 7.

Representation of Spaceship Operator

The spaceship operator is represented by the combination of three symbols, less than (<), equal (=), and greater than (>). The representation of the spaceship operator is <=>.

Use of Spaceship Operator

The spaceship operator is used for expression comparisons.

Syntax

Below is the syntax of the spaceship operator

operand_1 <=> operand_2

Return Value

The returns value of the spaceship operator is an int, it returns:

  • 0: If the values of both of the operands are equal.
  • -1: If the value of operand_2 is greater than operand_1.
  • 1: If the value of operand_1 is greater than operand_2.

Spaceship Operator Examples

Example 1: Comparing strings

<?php
echo ("abc" <=> "abc")."\n";
echo ("abc" <=> "aac")."\n";
echo ("abc" <=> "bca")."\n";
?>

The output of the above code is:

0
1
-1

Example 2: Comparing integers

<?php
echo (108 <=> 108)."\n";
echo (108 <=> 1008)."\n";
echo (108 <=> 51)."\n";
?>

The output of the above code is:

0
-1
1

Example 3: Comparing floats

<?php
echo (108.90 <=> 108.90)."\n";
echo (108.98 <=> 1008.898)."\n";
echo (108.89 <=> 51.12)."\n";
?>

The output of the above code is:

0
-1
1

Example 4: Comparing two arrays

<?php
$arr1 = array(10, 20, 30, 40, 50);
$arr2 = array(10, 20, 30, 40, 50);
$arr3 = array(20, 50, 30, 40, 40);

echo ($arr1 <=> $arr2)."\n";
echo ($arr1 <=> $arr3)."\n";
?>

The output of the above code is:

0
-1

To understand the above examples, you should have the basic knowledge of the following PHP topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.