本文介绍了在PHP中堆叠多个三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我写的:

 $Myprovince = (
($province == 6) ? "city-1" :
($province == 7) ? "city-2" :
($province == 8) ? "city-3" :
($province == 30) ? "city-4" : "out of borders"
);

但是对于每个字段,我都得到值city-4.我想使用三元运算符代替switch/if,因为我想尝试一下,看看它会如何实现.

But for every field I got the value city-4. I want to use ternary operators instead of switch/if because I want to experiment and see how it would be done.

此代码有什么问题?

推荐答案

其他人已经提出了正确的方法,但是如果您真的想使用三元运算符,则需要使用括号:

Others have already suggested the right way of doing it but if you really want to use ternary operator you need to use parenthesis as:

$province = 7;
 $Myprovince = (
 ($province == 6) ? "city-1" :
  (($province == 7) ? "city-2" :
   (($province == 8) ? "city-3" :
    (($province == 30) ? "city-4" : "out of borders")))
 );

更新的链接

这篇关于在PHP中堆叠多个三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 10:47