php中相应的嵌套三元运算符? [英] corresponding nested ternary operator in php?
本文介绍了php中相应的嵌套三元运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将以下 if if condition
转换为嵌套三元
运算符。
I want to convert following if else condition
to nested ternary
operator.
if ($projectURL) {
echo $projectURL;
} elseif ($project['project_url']) {
echo $project['project_url'];
} else {
echo $project['project_id'];
}
我写的如下。
echo ($projectURL)?$projectURL:($project['project_url'])?$project['project_url']: $project['project_id'];
但是发现它工作不正常。这不是正确的方法吗?
But it is found as not working properly.Is this not a right way?
推荐答案
三元运算符在PHP中是棘手的,因为它们是左关联的(与所有其他语言不同,它是右关联的)。在这种情况下,你需要使用括号来告诉PHP你想要什么:
Ternary operators are tricky thing in PHP, as they are left-associative (unlike all other languages, where it's right-associative). You will need to use parenthesis to tell PHP what you want exactly in this case:
echo ($projectURL ? $projectURL : ($project['project_url'] ? $project['project_url'] : $project['project_id']));
这篇关于php中相应的嵌套三元运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文