PHP多个三元运算符未按预期工作 [英] PHP multiple ternary operator not working as expected

查看:68
本文介绍了PHP多个三元运算符未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要打印2?

echo true ? 1 : true ? 2 : 3;

据我了解,它应该打印1.

With my understanding, it should print 1.

为什么它不能按预期工作?

Why is it not working as expected?

推荐答案

因为您编写的内容与以下内容相同:

Because what you've written is the same as:

echo (true ? 1 : true) ? 2 : 3;

并且您知道1被评估为true.

and as you know 1 is evaluated to true.

您期望的是:

echo (true) ? 1 : (true ? 2 : 3);

因此,请始终使用大括号来避免此类混淆.

So always use braces to avoid such confusions.

正如已经编写的那样,三元表达式在PHP中保留了关联性.这意味着,首先将在 left 中执行第一个,然后执行第二个,依此类推.

As was already written, ternary expressions are left associative in PHP. This means that at first will be executed the first one from the left, then the second and so on.

这篇关于PHP多个三元运算符未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆