In this lesson, you will learn about the Comparison Operators in PHP, their usage, and examples to better understand the topic.
The PHP comparison operators are given in the table below and used numeric values to perform the comparison operations.
Arithmetic Operators Symbol | Arithmetic Operators’ Names | Example |
---|---|---|
= | Equal | $a = $b |
!ERROR! A3 -> Formula Error: An unexpected error occurred | Identical | $a === $b |
!== | Not identical | $a !== $b |
<> | Not equal | $a <> $b |
! = | Not equal | $a != $b |
> | Greater than | $a > $b |
>= | Greater than equal to | $a >= $b |
< | Less than | $a < $b |
<= | Less than equal to | $a <= $b |
<=> | Spaceship | $a <=> $b |
Example
<?php echo "PHP Comparison Operator Example"; echo "<br>"; echo " ---------------------------------------- "; echo "<br>"; $a = 24; $b = 12; echo '$a = 24'; echo "<br>"; echo '$b = 12'; echo "<br>"; $Yes = 'Congratulations !! '; $No = 'Oops!! '; //Equal (=)operator checks if two operands are equal or not, In case it is yes then condition turns true. if ($a == $b) { echo $Yes, $a, " and ", $b, " operands are Equal "; } else { echo $No, $a, " and ", $b, " operands are not Equal "; } echo "<br>"; //Greater than (>)operator checks if value of 1st operand is greater than 2nd, then condition turns true. if ($a > $b) { echo $Yes, $a, " value operand is greater than ", $b; } else { echo $No, $a, " value operand is not greater than ", $b; } echo "<br>"; //Less than (<)operator checks if value of 1st operand is greater than 2nd, then condition turns true. if ($a < $b) { echo $Yes, $a, " value operand is less than ", $b; } else { echo $No, $a, " value operand is not less than ", $b; } echo "<br>"; //Notequal (!=)operator determine if two operands are equal or not, In case it is yes then condition turns true. if ($a != $b) { echo $Yes, $a, " is not equal to ", $b; } else { echo $No, $a, " is equal to ", $b; } echo "<br>"; //Less than or equal to operator checks if the value of 1st operand is greater than or equal to 2nd, then condition turns true. if ($a >= $b) { echo $Yes, $a, " is either greater than or equal to ", $b; } else { echo $No, $a, " is neither greater than nor equal to ", $b; } echo "<br>"; //Less than or equal to operator checks if value of 1st operand is less than or equal to 2nd, then condition turns true. if ($a <= $b) { echo $Yes, $a, " is either less than or equal to ", $b; } else { echo $No, $a, " is neither less than nor equal to ", $b; } ?>
Output
PHP Comparison Operator Example ---------------------------------------- $a = 24 $b = 12 Oops!! 24 and 12 operands are not Equal Congratulations !! 24 value operand is greater than 12 Oops!! 24 value operand is not less than 12 Congratulations !! 24 is not equal to 12 Congratulations !! 24 is either greater than or equal to 12 Oops!! 24 is neither less than nor equal to 12
This concludes the PHP Comparison Operators lesson. In the next lesson, you will learn about the Logical Operators in PHP.