Home > Article > Backend Development > How to use the combined comparison operator (<=>) in PHP7? (code example)
The combined comparison operator () is a very useful operator. This article will show you how to use the combined comparison operator (). I hope it will be useful to you. help.
Combined comparison operator ()
## operation operator is a three-way comparison operator that performs greater than, less than, and equality comparisons between two operands. [Video tutorial recommendation:PHP tutorial]
Example:$c = $a <=> $b; // 这相当于 $c = ($a < $b) ? -1 : (($a > $b) ? 1 : 0);
Explanation: The operator behaves like strcmp( ) or version_compare(); it can be used with integers, floats, strings, arrays, objects, etc.
The combined comparison provided by the operator:
● If the values on both sides are equal, 0 is returned ● If the left If the value on the right side is greater, return 1 ● If the value on the right side is greater, return -1Code example
Let’s use code examples to see how the operator performs combined comparisons.Example 1: Integer comparison
<?php echo"整数 <br>"; echo 7 <=> 7 ; echo"<br>"; echo 7 <=> 6; echo"<br>"; echo 6 <=> 7; ?>Rendering:
Example 2: Floating point number Comparison
<?php echo"浮点数<br>"; echo 2.5 <=> 1.5; echo"<br>"; echo 0.5 <=> 1.5; echo"<br>"; echo 1.5 <=> 1.5; ?>Rendering:
Example 3: String comparison
<?php echo"<br>字符串<br>"; echo "a" <=> "a" ; echo"<br>"; echo "g" <=> "b" ; echo"<br>"; echo "a" <=> "b" ; echo"<br>"; echo "A" <=> "B" ; echo"<br>"; echo "a" <=> "B" ; echo"<br>"; echo "2" <=> "1" ; echo"<br>"; echo "2" <=> "a" ; echo"<br>"; echo "2" <=> "A" ; ?>Rendering : Description: String comparison size, the comparison is the value of ascii code. The following are the ascii codes corresponding to some characters ● “0”~”9”: 48~57 ● “A”~“Z”: 65~90 ● “a”~”z”: 97~122
Example 4: Array comparison
<?php echo"<br>数组<br>"; echo [] <=> []; echo"<br>"; echo [1, 7, 3] <=> [1, 7, 3]; echo"<br>"; echo [1, 7, 3, 5] <=> [1, 7, 3]; echo"<br>"; echo [1, 7, 3] <=> [4, 4, 4]; echo"<br>"; ?>Rendering:
The above is the detailed content of How to use the combined comparison operator (<=>) in PHP7? (code example). For more information, please follow other related articles on the PHP Chinese website!