Comparison operators in PHP are used to compare two values. They return true
or false
based on the comparison result.
Operator | Name | Description | Example |
---|---|---|---|
== |
Equal | Returns true if values are equal. |
$a == $b |
=== |
Identical | Returns true if values and data types are equal. |
$a === $b |
!= or <> |
Not Equal | Returns true if values are not equal. |
$a != $b |
!== |
Not Identical | Returns true if values or data types are not equal. |
$a !== $b |
> |
Greater Than | Returns true if the left value is greater. |
$a > $b |
< |
Less Than | Returns true if the left value is smaller. |
$a < $b |
>= |
Greater Than or Equal | Returns true if the left value is greater or equal. |
$a >= $b |
<= |
Less Than or Equal | Returns true if the left value is smaller or equal. |
$a <= $b |
1. Equal (==)
Checks if two values are equal.
<?php $a = 10; $b = "10"; if ($a == $b) { echo "Equal"; } else { echo "Not Equal"; } ?>
2. Identical (===)
Checks if two values and their types are the same.
<?php $a = 10; $b = "10"; if ($a === $b) { echo "Identical"; } else { echo "Not Identical"; } ?>
3. Not Equal (!=)
Checks if two values are not equal.
<?php $a = 10; $b = 20; if ($a != $b) { echo "Not Equal"; } else { echo "Equal"; } ?>
4. Greater Than (>)
Checks if the left value is greater than the right value.
<?php $a = 15; $b = 10; if ($a > $b) { echo "$a is greater than $b"; } ?>
5. Less Than (<)
Checks if the left value is less than the right value.
<?php $a = 5; $b = 10; if ($a < $b) { echo "$a is less than $b"; } ?>
Conclusion
PHP comparison operators help evaluate conditions in decision-making. They return boolean values and are widely used in conditional statements like if
and loops.