【问题标题】:Multiple Statements For The Ternary Operator Of PHP [duplicate]PHP的三元运算符的多个语句[重复]
【发布时间】:2015-07-13 11:25:39
【问题描述】:

我想知道是否可以将三元运算符用于这样的事情:

var string = "";
if (something) {
  string = "foo"
} else if (somethingElse) {
  string = "bar";
} else if (bla) {
  string = "pool";
} else if (xxxxx) {
  string = "coffee";
} else {
  string = "";
}

据我所知,我可以用 Java 语言做到这一点:

String string = something?"foo":somethingElse?"bar":bla?"pool":xxxxx?"coffee":"";

但是我不确定PHP,我什至不确定在这种情况下使用三元运算符是否可以。

【问题讨论】:

  • 你可以,但不要!一系列 if/elseif/else 语句比嵌套三元运算符更具可读性和可理解性......并且调试成为痛苦管理的练习。 PHP 文档警告嵌套三元组出于某种原因违反直觉
  • 或者可以是switch-case
  • @MarkBaker 我明白了,谢谢。
  • @b0s3 是的,我会坚持下去的。

标签: php ternary-operator


【解决方案1】:

例如

 if (something) {
      string = "foo"
    } else if (somethingElse) {
      string = "bar";
    } else if (bla) {
      string = "pool";
    } else if (xxxxx) {
      string = "coffee";
    } else {
      string = "";
}

相当于在PHP中

(something) ? 'foo' : ((somethingElse) ? 'bar' : ((bla) ? 'pool' : ((xxxxx) ? 'coffe' : '')));

【讨论】:

  • 谢谢,但那些括号把我逼疯了,你能解释一下发生了什么吗?
猜你喜欢
  • 2019-12-30
  • 1970-01-01
  • 1970-01-01
  • 2013-02-13
  • 1970-01-01
  • 1970-01-01
  • 2016-12-08
  • 2011-01-19
相关资源
最近更新 更多