Curriculum
This tutorial will teach you about the PHP AND operator and how to use it to construct a complex logical expression.
The logical AND operator takes two operands and returns true if both are true; otherwise, it returns false.
The and keyword in PHP is used to represent the logical AND operator:
expression1 and expression2
The following table shows the outcome of the and operator:
expression1 | expression2 | expression1 and expression2 |
---|---|---|
true |
true |
true |
true |
false |
false |
false |
true |
false |
false |
false |
false |
Because PHP keywords are case-insensitive, the AND and and operators are identical:
expression1 AND expression2
By convention, the and operator should be used in lowercase.
In addition to the and keyword, PHP employs the logical AND operator &&
expression1 && expression2
The && and operators both produce the same result. The only distinction between the && and operators is their order of precedence.
The && operator takes precedence over the and operator. The order in which PHP evaluates operators is defined by their precedence.
Assume you want to give discounts to customers who buy more than three items that cost more than $99 each. To determine whether or not customers are eligible for a discount, use the AND operator as follows:
<?php $price = 100; $qty = 5; $discounted = $qty > 3 && $price > 99; var_dump($discounted);
Output
bool(true)
If you change the $quantity to 2, the $discounted will be false, as shown below:
<?php $price = 100; $qty = 2; $discounted = $qty > 3 && $price > 99; var_dump($discounted);
In practise, the logical AND operator will be used in the if, if-else, if-elseif, while, and do-while statements.
When the first operand’s value is false, the logical AND operator knows that the result must also be false. It does not evaluate the second operand in this case. This is known as short-circuiting.
Consider the following:
<?php $debug = false; $debug && print('PHP and operator demo!');
This is how it works.
To begin, define the variable $debug and set it to false.
Second, combine the $debug and print variables using the logical AND operator (). Because $debug is set to false, PHP does not evaluate the print() function call.
If you set $debug to true, you’ll see the following message in the output:
<?php $debug = true; $debug && print('PHP and operator demo!');
Output
PHP and operator demo!