为了账号安全,请及时绑定邮箱和手机立即绑定

在 echo 中使用三元运算符?

在 echo 中使用三元运算符?

PHP
慕沐林林 2023-08-06 10:42:33
为什么我可以这样使用 echo:<?php echo false ? 'yes' : 'no'; ?> //no但不能这样使用<?php echo false ?? 'yes'; ?> //nothing output
查看完整描述

2 回答

?
慕桂英546537

TA贡献1848条经验 获得超10个赞

这 ??PHP 中的运算符是空合并运算符:

expr1 ?? expr2;

expr1 is returned when expr1 exists and is NOT null; otherwise it returns expr2.

由于在本例中 expr1 为 false 但已设置,因此该表达式返回布尔值 false。

比较:

echo false ?? 'It is FALSE'; // won't be displayed
echo null ?? 'it is NULL'; // It will work

当传递布尔值 false 时,Echo 不会输出。


查看完整回答
反对 回复 2023-08-06
?
Cats萌萌

TA贡献1805条经验 获得超9个赞

如前所述,您在这里使用空合并运算符

它正在检查 false 是否为空

只是想添加:常规与简写三元运算

echo false ? 'yes' : 'no';

是相同的

echo false ?: 'no';

所以,

echo true ?: 'no';

将输出 1,因为 ?: 本质上跳过第一个表达式

(condition) ? expression1 : expression2


查看完整回答
反对 回复 2023-08-06
  • 2 回答
  • 0 关注
  • 96 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信