php逻辑运算

测试你的逻辑思维,做最强大脑~~

$a =5;

$b=10;

要求在不引入任何其他函数的前提下,互换$a和$b的值,即 $a=10,$b=5;


答案:

$a = $a+$b;//$a =15,$b=10;

$b = $a-$b;//$a=15,$b=5;

$a = $a-$b;//$a=10,$b=5;

就得出了 $a=10;$b=5;

### PHP 中的逻辑运算符及其用法 #### 1. **and (逻辑与)** `and` 运算符返回 `true`,仅当两个操作数都为 `true` 的时候。它通常用于条件语句中连接多个布尔表达式。 ```php $a = true; $b = false; if ($a and $b) { echo "Both are true"; } else { echo "At least one is false"; // 输出此行 } ``` 上述代码展示了 `and` 的基本功能[^3]。 --- #### 2. **or (逻辑或)** `or` 运算符返回 `true`,只要其中一个操作数为 `true` 即可。 ```php $a = true; $b = false; if ($a or $b) { echo "At least one is true"; // 输出此行 } else { echo "Both are false"; } ``` 这里可以看到 `or` 如何判断至少有一个条件成立的情况。 --- #### 3. **xor (逻辑异或)** `xor` 返回 `true`,只有在两个操作数中有且只有一个为 `true` 时才成立。 ```php $a = true; $b = false; if ($a xor $b) { echo "Exactly one is true"; // 输出此行 } else { echo "Either both are true or both are false"; } ``` 这段代码说明了 `xor` 只允许单一真存在的特性[^2]。 --- #### 4. **not (逻辑非)** `not` 是单目运算符,用于取反一个布尔的结果。 ```php $a = true; if (! $a) { echo "This will not be printed"; } else { echo "The value of a was inverted to false"; // 输出此行 } ``` 通过这个例子可以看出 `!` 对于反转布尔的作用。 --- #### 5. **&& 和 || (短路逻辑运算符)** 虽然 `and` 和 `or` 更具可读性,但在实际开发中更常用的是 `&&` 和 `||`,因为它们支持短路求(short-circuit evaluation),从而提高性能。 - `&&`: 类似于 `and`。 - `||`: 类似于 `or`。 ```php $a = true; $b = false; // 使用 && if ($a && $b) { echo "Both must be true"; } else { echo "One or more conditions failed"; // 输出此行 } // 使用 || if ($a || $b) { echo "At least one condition passed"; // 输出此行 } else { echo "All conditions failed"; } ``` 这些符号的行为类似于其对应的单词版本,但优先级更高[^1]。 --- ### 总结表格 | 符号 | 名称 | 描述 | |------|------------|----------------------------------------------------------------------------------------| | `and`| 逻辑与 | 如果 `$a` 和 `$b` 均为 `true` 则返回 `true` | | `or` | 逻辑或 | 如果 `$a` 或 `$b` 至少一个是 `true` 则返回 `true` | | `xor`| 逻辑异或 | 如果 `$a` 或 `$b` 恰好一个是 `true` 而另一个不是,则返回 `true` | | `!` | 逻辑非 | 将输入取反 | | `&&` | 短路逻辑与 | 同 `and`,但有更高的优先级 | | `||` | 短路逻辑或 | 同 `or`,但有更高的优先级 | 以上总结涵盖了 PHP 中常见的逻辑运算符以及其实现方式。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值