Php 简明教程
PHP - Logical Operators Examples
在 PHP 中,逻辑运算符用于组合条件语句。这些运算符允许你通过将多个条件组合在一起创建更复杂的条件。
In PHP, logical operators are used to combine conditional statements. These operators allow you to create more complex conditions by combining multiple conditions together.
逻辑运算符通常用在 if, while 等条件语句中,以及 for 循环中,用以根据特定条件控制程序执行的流程。
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.
下表重点介绍了 PHP 支持的逻辑运算符。
The following table highligts the logical operators that are supported by PHP.
假设变量 $a 保存 10,变量 $b 保存 20,则 -
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. |
Example
以下示例演示如何在 PHP 中使用这些逻辑运算符 -
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";
}
?>
它将生成以下 output −
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