There are following logical operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then:
Operator | Description | Example |
---|---|---|
and | Called Logical AND operator. If both the operands are true then then condition becomes true. | (A and B) is true. |
or | Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. | (A or B) is true. |
&& | Called Logical AND operator. If both the operands are non zero then then condition becomes true. | (A && B) is true. |
|| | Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. | (A || B) is true. |
! | Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. | !(A && B) is false. |
PHP Logical Operators Example
<html> <head><title>Logical Operators</title><head> <body> <?php $a = 42; $b = 0; if( $a && $b ){ echo "TEST1 : Both a and b are true<br/>"; }else{ echo "TEST1 : Either a or b is false<br/>"; } if( $a and $b ){ echo "TEST2 : Both a and b are true<br/>"; }else{ echo "TEST2 : Either a or b is false<br/>"; } if( $a || $b ){ echo "TEST3 : Either a or b is true<br/>"; }else{ echo "TEST3 : Both a and b are false<br/>"; } if( $a or $b ){ echo "TEST4 : Either a or b is true<br/>"; }else{ echo "TEST4 : Both a and b are false<br/>"; } $a = 10; $b = 20; if( $a ){ echo "TEST5 : a is true <br/>"; }else{ echo "TEST5 : a is false<br/>"; } if( $b ){ echo "TEST6 : b is true <br/>"; }else{ echo "TEST6 : b is false<br/>"; } if( !$a ){ echo "TEST7 : a is true <br/>"; }else{ echo "TEST7 : a is false<br/>"; } if( !$b ){ echo "TEST8 : b is true <br/>"; }else{ echo "TEST8 : b is false<br/>"; } ?> </body> </html>
This will produce following result
TEST1 : Either a or b is false TEST2 : Either a or b is false TEST3 : Either a or b is true TEST4 : Either a or b is true TEST5 : a is true TEST6 : b is true TEST7 : a is false TEST8 : b is false