2009-08-15 109 views
-4

在PHP中,在下面的邏輯允許PHP條件邏輯

If (x && y) 
    //Do A 
Elseif (x) 
    // Do B 
Elseif (y) 
    // Do C 
Else 
    // Do D 

基本上,是你允許使用超過一種ELSEIF更?

+9

你爲什麼不能只是測試呢? – jkeys 2009-08-15 01:34:49

回答

2

if(this == this && this == this){ 
    //this and that 
}else if(this == that || this == that){ 
    //this or that 
}else{ 
    //anything else 
} 
+1

不要忘記你的$和== – Moak 2009-08-15 01:20:21

+1

我還會指出你正在使用賦值運算符(=)而不是比較檢查(==)。 – 2009-08-15 01:40:13

11

是:對HTML文件

<?php if ($x && $y): ?> 
    Element A 
<?php elseif ($x): ?> 
    Element B 
<?php elseif ($y): ?> 
    Element C 
<?php else: ?> 
    Element D 
<?php endif;?> 
+0

else和if之間的空格在PHP中不是必需的 - 有一個elseif控制語句。 – 2009-08-15 01:16:36

+2

番茄/西紅柿;)只是更習慣於寫'else if' – gnarf 2009-08-15 01:21:42

+0

+1實際花費時間回答這個問題 – 2009-08-15 03:44:28

2

是的,雖然如果測試是簡單($a == $b),使用開關代替

if ($x && $y) { 
    //Do A 
} else if ($x) { 
    // Do B 
} else if ($y) { 
    // Do C 
} else { 
    // Do D 
} 

另一個格式有用:

switch ($a) { 
    case $b: 
     break; 
    case $c: 
     break; 
    default: 
     //Like else 
    } 
2

您可以使用

if($x) 
    // for one line of code 
elseif($y) 
    // also for one line of code 

if($x) { 
    // for more than 
    // one line of code 
} elseif($y) { 
    // also for multi- 
    // line codes 
} 

if($x): 
    // multi-line 
endif;