0

我正在练习陈述并遇到了问题。我正在努力做到这一点,如果$child3有空,那么echo三个孩子都可以,比如什么时候$child2有空,它echo是 Kim & Pom。我做错了什么?

$child = "Kim";
$child2 = "Pom";
$child3 = "Rob";

if($child2) {
    echo $child; echo " "; echo $child2;
} elseif($child3) {
    echo $child; echo " "; echo $child2; echo " "; echo $child3;
} else {
    echo $child;
}
4

7 回答 7

1

elseifif仅当前面的s 或s均未执行时才执行elseif。因此,您需要将其移至另一个上方if

if($child3) {
    echo $child; echo " "; echo $child2; echo " "; echo $child3;
} elseif($child2) {
    echo $child; echo " "; echo $child2;
} else {
    echo $child;
}
于 2012-06-11T23:31:30.330 回答
1

尝试颠倒条件:

$child = "Kim";
$child2 = "Pom";
$child3 = "Rob";

if($child3){
    echo $child . " " . $child2 . " " . $child3;
}else if($child2){
    echo $child . " " . $child2;
}else{
    echo $child;
}

您可能还喜欢美妙的字符串连接运算符.

于 2012-06-11T23:31:32.983 回答
1

可能你想要这样的东西:

$child = 1; // Or $child = 2; Or $child = 3;

if ($child == 1) {
    echo 'Kim';
} elseif ($child == 2) {
    echo 'Pom';
} else {
    echo 'Rob';
}

但我建议switch()你一有elseif

于 2012-06-11T23:34:03.370 回答
0
$child = "Kim";
$child2 = "Pom";
$child3 = "Rob";

if($child3){
    echo $child; echo " "; echo $child2; echo " "; echo $child3;
}elseif($child2){
    echo $child; echo " "; echo $child2;
}else{
    echo $child;
}
于 2012-06-11T23:31:59.840 回答
0

如果那是您的实际代码,那么您只会得到Kim Rob$child2一如既往true,从而绕过您的else子句。

此外,您可以将您echo的 s 组合成:

echo "$child $child2 $child3";

它使以这种方式阅读变得容易得多。

于 2012-06-11T23:32:22.617 回答
0

这个怎么样?

if ($child) {
   echo "{$child} ";
}
if ($child2) {
   echo "{$child2} ";
}
if ($child3) {
   echo "{$child3} ";
}
于 2012-06-11T23:33:28.113 回答
0

这就是我将如何做到的。我同意 Dragon 的观点,即切换会更清晰/更好。

switch (true)
{
  case (isset($child,$child2,$child3)) : 
    echo $child . ' ' . $child2 . ' ' . $child3;
    break;
  case (isset($child, $child2)) :
    echo $child . ' ' . $child2;
    break;
  case (isset($child)) :
    echo $child;
    break;
}
于 2012-06-12T00:00:52.617 回答