2017-04-07 63 views
0

我有以下代碼,並想知道是否有更好的方式使用if-else具有相同的結果,而不是使用相同的其他三次?嵌套if-else語句與其他代碼

if($condition1) { 
    // some code to get condition 2 
    if($condition2) { 
     // some code to get condition 3 
     if($condition3) { 
     $dt = $something; 
     } else { 
     $dt = ""; 
     } 
    } else { 
     $dt = ""; 
    } 
} else { 
    $dt = ""; 
} 
+1

定義varibale'$ DT = 「」'之前,如果第一級的if語句。那麼你不需要寫其他部分。 – Gaurav

+0

你爲什麼不去開關條件?這將有利於你的條件。 –

回答

1

你可以很容易地擺脫一些額外的else陳述。

$dt = ""; // Assign $dt in the beginning 

if ($condition1) { 
    // some code to get condition 2 
    if ($condition2 && $condition3) { 
     // some code to get condition 3 
     $dt = $something; 
    } 
} 
0

避免嵌套語句的兩種方法。

使用功能

$dt = doSomething($params); 

function someFunction ($params) { 

    if (!$condition1) { 
     return ""; 
    } 

    // do stuff for condition 1 

    if (!$condition2) { 
     return ""; 
    } 

    // do stuff for condition 2 

    if (!$condition3) { 
     return ""; 
    } 

    return $something; 
} 

使用DO/while語句

do { 

    $dt = ""; 

    if (!$condition1) { 
     break; 
    } 

    // do stuff for condition 1 

    if (!$condition2) { 
     break; 
    } 

    // do stuff for condition 2 

    if (!$condition3) { 
     break; 
    } 

    $dt = $something; 

} while (0); // since this will evaluate to false it will not loop at all.