具有 3 种可能性的 if 结构的最佳方法

Most optimal way for if structure with 3 possibilities

本文关键字:结构 最佳 方法 if 具有 可能性      更新时间:2023-09-26

编写具有 3 种可能性的 if 结构(或开关或大小写或 w/e)的最佳方法是什么。

if($tekst!=''){
$qry="tekst filled in";
}
elseif($aantal!=''){
$qry="aantal filled in";
}
elseif($aantal!=''&&$tekst!='')
{
$qry="both filled in";
}

这不适合堆栈溢出。你的问题可能是 闭。我只是警告你

。只是有人想要编码风格的建议...

switch 语句不可用,因为合并检查 ($aantal!=''&$tekst!='')。所以 if/else 语句是您的最佳选择(恕我直言)。但是,我会把它写成:

if($aantal && $tekst) {
   $qry="both filled in";
}
else if($tekst) {
    $qry="tekst filled in";
}
else if($aantal) {
    $qry="aantal filled in";
}

我个人觉得这样更易读。

注意:在发布问题之前,请务必将本地化敏感文本写入英语。

在什么意义上是最优的?

一个想法是:

var r = [ [ undefined,  "tekst filled in" ],
          [ "aantal filled in", "both filled in" ]];
$qry = r[+($aantal!='')][+($tekst!='')];

+运算符用于将"false"计算为 0,将"true"计算为 1 以进行索引。R也可以定义为具有键"true"和"false"的对象:

r = { "true" : { "true": "Both filled in", "false": "tekst filled in" },
      "false" : { "true": "aantal filled in" } };
$qry = r[$aantal!=''

][$tekst!=''];

if(something) {
    ...
}
else if(something-else-specific) { /* other specific case */
    ...
}
else { /* any other cases*/
   ...
}

仅此而已。