2013-08-06 30 views
1

我將嘗試用註釋代碼解釋我想實現的內容。如果條件符合,則跳過if語句並繼續執行下面的代碼php

我想要做的是跳過if語句,如果條件滿足並繼續執行條件語句之外的代碼。

<?php 
    if (i>4) { 
    //if this condition met skip other if statements and move on 
    } 

    if (i>7) { 
    //skip this 
?> 

<?php 
    move here and execute the code 
?> 

我知道break,continue,end和return語句,但這不適用於我的情況。

我希望這可以清除我的問題。

+0

中斷並繼續工作只在循環內。 –

+1

你可以簡單地包裝什麼應該跳過一個else語句?這是我認爲如果 - 其他 - 是有原因的。正如有人早些時候所說的那樣:if(i> 4)和if(i> 7)如何相關。如果他們應該使用if(i> 7)應該是第一個檢查條件。 – Alex

回答

1

我通常設置某種標記,如:

<?php 
    if (i>4) 
    { 
    //if this condition met skip other if statements and move on 
    $skip=1; 
    } 

    if (i>7 && !$skip) 
    { 
    //skip this 
    ?> 

    <?php 
    move here and execute the code 
    ?> 
4

如果你的第一個條件滿足,你想跳過其他條件,你可以使用任何標誌變量如下:

<?php 
     $flag=0; 
     if (i>4) 
     { 
      $flag=1; 
     //if this condition met skip other if statements and move on 
     } 

     if (i>7 && flag==0) 
     { 
     //skip this 
     ?> 

     <?php 
     move here and execute the code 
     ?> 
+0

爲什麼不把其他的if語句放在第一個「else」中呢? –

2

您可以使用goto

<?php 
if (i>4) 
{ 
//if this condition met skip other if statements and move on 
goto bottom; 
} 

if (i>7) 
{ 
//skip this 
?> 

<?php 
bottom: 
// move here and execute the code 
// } 
?> 

但是再一次,尋找恐龍。

goto xkcd

3

使用if-elseif-else

if($i > 4) { 
    // If this condition is met, this code will be executed, 
    // but any other else/elseif blocks will not. 
} elseif($i > 7) { 
    // If the first condition is true, this one will be skipped. 
    // If the first condition is false but this one is true, 
    // then this code will be executed. 
} else { 
    // This will be executed if none of the conditions are true. 
} 

結構上,這應該是你在找什麼。儘量避免任何會導致意大利麪代碼的東西,如goto,breakcontinue

在附註中,您的條件沒有多大意義。如果$i不大於4,它永遠不會大於7,所以第二個塊永遠不會被執行。

0
<?php 
    while(true) 
    { 
    if (i>4) 
    { 
    //if this condition met skip other if statements and move on 
    break; 
    } 

    if (i>7) 
    { 
    //this will be skipped 
    } 
    }  
?> 

    <?php 
    move here and execute the code 
    ?> 
+0

如果你想避免無限循環期間所有false..use int i = 0; while(i <1){//你的if語句;我++; –

相關問題