Logical Operators in PHP with Example

phpWe have seen how comparison operators work in PHP with conditional statements.  Comparison operators compare 2 values and return boolean value (true or false).  But we do encounter some scenarios where we want to make our judgement based on 2 boolean values returned by 2 conditions.  In such scenario, logical operators comes into play.  Most commonly used logical operators are given below.  In the below given example, consider $a and $b as boolean values.

Operator Name Meaning
&& AND True if $a and $b both are true.
|| OR True if $a or $b is true.
! Not True if $a is false or False if $a is true.

 

Example of logical operators in PHP is given below.

<?php 

$a = 5;
$b = 6;
$c = 5;
$d = 6;

//AND Operator
if(($a == $c) && ($b == $d)){
	echo("AND Operator = True, ");
}

//OR Operator
if(($a == $d) || ($b == $d)){
	echo("OR Operator = True, ");
}

//NOT Operator
if(!($a == $d)){
	echo("Not Operator = True");
}

?>