Home >>PHP Tutorial >PHP Comparative Operators

PHP Comparative Operators

PHP comparative operators

PHP lets you Compare one variable or value with another via its wide range of comparison operators.
Common Comparison Operators
Operatos Description
== Equal to
=== Equal to and of the same type
!= Not equal to
!== Not equal to and of the same type
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Here's example illustrating these operators in action

Eg ( == and === )
<?php
	
$x=10;
	
$y=10.0;
	
echo ($x==$y);
//it returns true because both the variable contains same value.
	
echo ($x===$y);
/*it returns false because === strongly compares.
here both variable contain same value i.e 10 but different datatype one is integer and another is float.*/ 

?>

in the above example. Two variable $x , $y define $x hold the value 10 $y hold value 10.0 Now perform several operation on this First check ($x==$y)=>it returns true because the value for both is same Second Check($x===$y)=>it returns false because now it also compare data-type. $y hold a float value.

Difference between ( == and === )

<?php
	
//another example
$bool=(boolean)1;
	
$int=(integer)1;
		
//return true because both have same value.
echo ($bool==$int);
		
//return false because both have same value but diff data type
echo ($bool===$int);	

?>	

$bool=(boolean)1 ($bool==$int) it returns true because both have same value $int= (integer)1 ($bool===$int) its return false because both have different data type

Use of( >, <, >=, <= )

<?php	

$a=10;
		
$b=11;
			
echo $a>$b;
//return false because $a is less than $b.
				
echo $a<$b;
//return true because $a is less than $b.
		
echo $a>=$b;
//return false because neighter $a is greater nor equal to $b
		
		
echo $a<=$b;
//return true because $a is than $b.
			
?>


$a hold the value 10 $b hold the value 11 check ($a>$b)=> returns false because $a less than $b. check($a>=$b)=> returns true because $a neighter grater nor equal to $b.

No Sidebar ads