Home > Article > Backend Development > How to use php logical operators
This time we will discuss the application of logical operators in PHP. Logical operators (1) &&(and) logical AND (2) ||(or) logical OR (3) !(not) logical NOT, unary operator. (4) xor logical difference.
The concept of logical operators:
Perform logical operations on expressions, and the result of the operation is a Boolean value (true, false). The value of the expression required to participate in the logical operation is a Boolean type value. If not, it will be automatically converted into a Boolean type value by PHP.
When the values of the expressions on the left and right sides are both true, the result of the operation is true, and vice versa. As long as one of them is false, the operation result is false;
Except the following values will be considered false, other values will be considered true:
Boolean value false
0
Floating point 0.0
Blank string and string 0
Array without members
null
Let’s look at an example:
<?php $x=true; $y=true; var_dump($x && $y); ?>
Obviously the result is bool(true). From this example we can see that when both expressions are true, the result is true.
One of the values of the expressions on the left and right sides is true, and the result of the operation is true. Only when the values on both sides are false, the result is is false. We changed the value of $y in the previous example to false, and we can find that the result became false.
When the values of the left and right expressions are different, it is true, otherwise it is false. Let’s look at the example just now. The values of $x and $y are the same, so the result is false.
Negate the value of the original expression. It was originally false and now it is true, and vice versaIt is the opposite.
<?php $x=true; var_dump(!$x); ?>
We can look at this example. Based on the above conclusion, it is easy to find that the answer to this example is bool (false).
These examples intuitively explain to us the operation rules of logical operators AND, OR, XOR and NOT, and there is no need for too much description.
In PHP, we can use parentheses to treat a certain part of the expression as a whole. Although there are places where parentheses are not required, they can also be added to increase the readability of the statement and facilitate follow-up. operate.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to use php logical operators. For more information, please follow other related articles on the PHP Chinese website!