PHP - logical operators
Logical operators are used to combine two or more conditions. PHP has following logical operators:
- && - logical AND operator
- and - logical AND operator
- || - logical OR operator
- or - logical OR operator
- ! - logical NOT operator
- xor - logical exclusive OR operator
Logical AND operator (&& / and)
The logical AND operator is used to combine two or more conditions and returns true only when all conditions are true, otherwise returns false. Consider the example below to understand this concept:
<?php function range_func($x){ //&& (and) operator is used to combine conditions //returns true only when x >= 10 and x <= 25 if($x >= 10 and $x <= 25) echo "$x belongs to range [10, 25].\n"; else echo "$x do not belongs to range [10, 25].\n"; } range_func(15); range_func(25); range_func(50); ?>
The output of the above code will be:
15 belongs to range [10, 25]. 25 belongs to range [10, 25]. 50 do not belongs to range [10, 25].
Logical OR operator (|| / or)
The logical OR operator is used to combine two or more conditions and returns true when any of the conditions is true, otherwise returns false. Consider the following example:
<?php function range_func($x){ //|| (or) operator is used to combine conditions //returns true when either x < 100 or x > 200 if($x < 100 or $x > 200) echo "$x do not belongs to range [100, 200].\n"; else echo "$x belongs to range [100, 200].\n"; } range_func(50); range_func(100); range_func(150); ?>
The output of the above code will be:
50 do not belongs to range [100, 200]. 100 belongs to range [100, 200]. 150 belongs to range [100, 200].
Logical NOT operator (!)
The logical NOT operator is used to return opposite boolean result. Consider the example below:
<?php function range_func($x){ //! operator is used to return //true when x <= 100 if(!($x >= 100)) echo "$x is less than 100.\n"; else echo "$x is greater than or equal to 100.\n"; } range_func(50); range_func(100); range_func(150); ?>
The output of the above code will be:
50 is less than 100. 100 is greater than or equal to 100. 150 is greater than or equal to 100.
Logical XOR operator (xor)
The logical XOR operator returns true when any of the conditions is true, but not both, otherwise returns false. Consider the following example:
<?php function range_func($x){ //xor operator returns true when either //x >= 100 or x <= 200; returns false //when either both or none condition is true if($x >= 100 xor $x <= 200) echo "$x do not belongs to range [100, 200].\n"; else echo "$x belongs to range [100, 200].\n"; } range_func(50); range_func(100); range_func(150); ?>
The output of the above code will be:
50 do not belongs to range [100, 200]. 100 belongs to range [100, 200]. 150 belongs to range [100, 200].
❮ PHP - Operators