”;
In PHP, logical operators are used to combine conditional statements. These operators allow you to create more complex conditions by combining multiple conditions together.
Logical operators are generally used in conditional statements such as if, while, and for loops to control the flow of program execution based on specific conditions.
The following table highligts the logical operators that are supported by PHP.
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 condition becomes true. | (A and B) is true |
or | Called Logical OR Operator. If any of the two operands are non zero then condition becomes true. | (A or B) is true |
&& | Called Logical AND operator. The AND operator returns true if both the left and right operands are true. | (A && B) is true |
|| | Called Logical OR Operator. If any of the two operands are non zero 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 |
Example
The following example shows how you can use these logical operators in PHP −
<?php $a = 42; $b = 0; if ($a && $b) { echo "TEST1 : Both a and b are true n"; } else { echo "TEST1 : Either a or b is false n"; } if ($a and $b) { echo "TEST2 : Both a and b are true n"; } else { echo "TEST2 : Either a or b is false n"; } if ($a || $b) { echo "TEST3 : Either a or b is true n"; } else { echo "TEST3 : Both a and b are false n"; } if ($a or $b) { echo "TEST4 : Either a or b is true n"; } else { echo "TEST4 : Both a and b are false n"; } $a = 10; $b = 20; if ($a) { echo "TEST5 : a is true n"; } else { echo "TEST5 : a is false n"; } if ($b) { echo "TEST6 : b is true n"; } else { echo "TEST6 : b is false n"; } if (!$a) { echo "TEST7 : a is true n"; } else { echo "TEST7 : a is false n"; } if (!$b) { echo "TEST8 : b is true n"; } else { echo "TEST8 : b is false"; } ?>
It will produce the following output −
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
Advertisements
”;