不寻常的三元运算 [英] unusual ternary operation

查看:82
本文介绍了不寻常的三元运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要求我执行三元运算符使用的此操作:

I was asked to perform this operation of ternary operator use:

$test='one';

echo $test == 'one' ? 'one' :  $test == 'two' ? 'two' : 'three';

哪个打印两个(使用php检查).

Which prints two (checked using php).

我仍然不确定这样做的逻辑.拜托,任何人都可以告诉我这样做的逻辑.

I am still not sure about the logic for this. Please, can anybody tell me the logic for this.

推荐答案

好吧?和:具有相同的优先级,因此PHP将按从左到右的顺序分析每个位:

Well, the ? and : have equal precedence, so PHP will parse left to right evaluating each bit in turn:

echo ($test == 'one' ? 'one' :  $test == 'two') ? 'two' : 'three';

第一个$test == 'one'返回true,因此第一个括号的值为'one'.现在,第二元的计算如下:

First $test == 'one' returns true, so the first parens have value 'one'. Now the second ternary is evaluated like this:

'one' /*returned by first ternary*/ ? 'two' : 'three'

一个"为真(非空字符串),因此最终结果为两个".

'one' is true (a non-empty string), so 'two' is the final result.

这篇关于不寻常的三元运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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