Logical Operators : PHP



PHP Logical Operators :

Consider the value of A is 10 and B is 20 then –

Operator Description Example
and If both the operands are true then then condition becomes true (A and B) is true.
or If any of the two operands are non zero then then condition becomes true (A or B) is true.
'&&' If both the operands are non zero then then condition becomes true (A && B) is true.
|| If any of the two operands are non zero then then condition becomes true (A || B) is true.
! Used to reverses the logical state of its operand !A is false and !B is also false.
<html>
<head><title>Logical Operators</title><head>
<body>

<?php
    $num1 = 50;
    $num2 = 0;

    if( $num1 && $num2 ){
       echo "Test1 : num1 & num2 are true<br/>";
    }else{
       echo "Test1 : either num1 or num2 is false<br/>";
    }

    if( $num1 || $num2 ){
       echo "Test2 : num1 or num2 is true<br/>";
    }else{
       echo "Test2 : num1 & num2 are false<br/>";
    }
	
    if( $num1 and $num2 ){
       echo "Test3 : num1 & num2 are true<br/>";
    }else{
       echo "Test3 : either num1 or num2 is false<br/>";
    }
	
    if( $num1 or $num2 ){
       echo "Test4 : num1 or num2 is true<br/>";
    }else{
       echo "Test4 : num1 & num2 are false<br/>";
    }
?>

</body>
</html>

Output :

Test1 : either num1 or num2 is false
Test2 : num1 or num2 is true
Test3 : either num1 or num2 is false
Test4 : num1 or num2 is true

Example 2 : Logical Operators

<html>
<head>
   <title>Logical Operators</title>
<head>
<body>

<?php
    $num1 = 50;

    if($num1){
       echo "Test1 : true condition<br/>";
    }else{
       echo "Test1 : false condition<br/>";
    }

    if(!$num1){
       echo "Test2 : true condition<br/>";
    }else{
       echo "Test2 : false condition<br/>";
    }
?>

</body>
</html>

Output :

Test1 : true condition
Test2 : false condition