PHP Comparison Operators
PHP comparison operators are used compare one variable value with another. Values may be string or number.
The PHP basic comparison operators
== Equal $a==$b
=== Equal Identical $a===$b
!= Not Equal $a!=$b
!== Not Equal Identical $a!==$b
> Greater than $a>$b
< Less than $a<$b
>= Greater than or equal to $a>=$b
<= Less than or equal to $a<=$b
== Equal comparison operator example
In below example return true if $a is equal to $b.
<?php
$a =5;
$b =5;if($a==$b)
{
echo “Equal”;
}
else
{
echo “Not Equal”
}?>
The output is:
Equal
In above php example $a and $b both valribles value are same, then if condition return true and print “Equal” in output.
=== Equal Identical comparison operator example
In below example return true if $a is equal to $b and must be same data type.
<?php
$a =5;
$b =5.0;if($a===$b)
{
echo “Equal”;
}
else
{
echo “Not Equal”;
}?>
The output is:
Not Equal
In above php example $a and $b both variables value are same, but different data type so if condition not satisfied the answer is “Not Equal”.
!= Not Equal comparison operator example
In below example return true if $a is not equal to $b.
<?php
$a =5;
$b =2;if($a !=$b)
{
echo “Equal”;
}
else
{
echo “Not Equal”;
}?>
The output is:
Equal
In above php example $a and $b both variables value are not same, then if condition return true and print “Equal” in output.
!== Not Equal Identical comparison operator example
In below example return true if $a is not equal to $b and must be same type.
<?php
$a =5;
$b =2.5;if($a!==$b)
{
echo “Equal”;
}
else
{
echo “Not Equal”
}?>
The output is:
Equal
> Greater than and >= Greater than or Equal to example
In below php example return true if $a is greater than to $b.
<?php
$a =5;
$b =2;if($a>$b)
{
echo “a is bigger than b”;
}
else if($a>=$b)
{
echo “a is equal to b”;
}
else
{
echo “a is smaller than b”;
}?>
The output is:
a is bigger than b
In above php example the result is “a is bigger than b” because $a value bigger than $b value.
$a=5 and $b=2 here $a value is grater than $b value.
The first if condition returns true if only $a is greater than $b.
If $a=5 and $b=5, then the second if condition will be true and result is “a is equal to b”.
< Less than and <= Less than or Equal to example
In below example return true if $a is less than to $b.
<?php
$a =5;
$b =2;if($a<$b)
{
echo “a is smaller than b”;
}
else if($a<=$b)
{
echo “a is equal to b”;
}
else
{
echo “a is bigger than b”;
}?>
The output is:
a is bigger than b
Here, $a=5 and $b=2, so $a is not smaller and not equal to $b. The both if condition not satisfy then result will be else condition “a is bigger than b”.