Latest web development tutorials

PHP spaceship operator (comparison operator combination)

PHP spaceship operator (comparison operator combination)

PHP 7 New Features PHP 7 New Features

PHP 7 additional spacecraft operators (combination of comparison operators) used to compare two expressions$ a and $ b,if$ ais less than, equal to or greater than$ b,it returns -1, 0 or 1, respectively.

Examples

<?php
// 整型比较
print( 1 <=> 1);print(PHP_EOL);
print( 1 <=> 2);print(PHP_EOL);
print( 2 <=> 1);print(PHP_EOL);
print(PHP_EOL); // PHP_EOL 为换行符

// 浮点型比较
print( 1.5 <=> 1.5);print(PHP_EOL);
print( 1.5 <=> 2.5);print(PHP_EOL);
print( 2.5 <=> 1.5);print(PHP_EOL);
print(PHP_EOL);

// 字符串比较
print( "a" <=> "a");print(PHP_EOL);
print( "a" <=> "b");print(PHP_EOL);
print( "b" <=> "a");print(PHP_EOL);
?>

The above program execution output is:

0
-1
1

0
-1
1

0
-1
1

PHP 7 New Features PHP 7 New Features