如果声明有2个条件

时间:2012-06-11 23:28:33

标签: php if-statement

我正在练习语句并遇到了问题。我试图让它如果$child3可用,那么它将echo所有三个孩子,就像$child2何时可用,echo s Kim& ;双响炮。我做错了什么?

$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;
}

7 个答案:

答案 0 :(得分:1)

elseif仅在前面的ifelseif没有执行时执行。所以你要将它移到另一个if

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

答案 1 :(得分:1)

尝试颠倒条件:

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

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

您可能也喜欢精彩的字符串连接运算符.

答案 2 :(得分:1)

可能你想要这样的东西:

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

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

但是,只要您switch(),我就会推荐elseif

答案 3 :(得分: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;
}

答案 4 :(得分:0)

如果这是您的实际代码,您将只获得Kim Rob,因为$child2始终为true,从而绕过您的else条款。

此外,您可以将echo合并到:

echo "$child $child2 $child3";

这样可以更容易地阅读。

答案 5 :(得分:0)

这个怎么样?

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

答案 6 :(得分: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;
}