[英]IF vs. SWITCH and which is more suitable for this job and why?
我想知道是否有可能在switch語句/案例中復制這種檢查:
if(isset($_POST["amount"]) && (isset($_POST["fruit"]))) {
$amount = $_POST['amount'];
$fruit = $_POST['fruit'];
if($fruit == "Please select a fruit") {
echo "<script>alert('Required Field: You must choose a fruit to receive your total')</script>";
} else if(empty($fruit) or ($amount<=0) or ($amount>50)) {
echo "<script>alert('Required Field: You must enter an amount between 0-50g to receive your total')</script>";
} ... and further on
注意:我將更加關注可以在一個IF中簡單完成的&&
比較,以及是否有可能在切換情況下完成並接收嵌套if / else這樣的結果。 如果不可能,為什么呢? 哪種方法更有效?為什么?
我寧願使用If-Else If條件,也不願將其轉換為Switch語句。 您必須認識到switch語句僅接受一個參數:
switch($arg)
在您的情況下, amount
為$_POST["amount"]
, fruit
為$_POST["fruit"]
。 您的第一個問題是如何在switch語句中傳遞這2個值。
在這種情況下,您不能使用開關,因為您正在檢查兩個產生boolean
結果的變量的條件( isset
)。 那么實際上你可以做一個switch
這個條件,並在真實的情況下,切換到該代碼,並在假到代碼的情況。 但是,恕我直言,這沒有多大意義。 在開關中,您只需要檢查一個變量或表達式,就可以執行無論該開關求值結果如何的代碼。 因此,不能,您不能使用這些嵌套的if進行切換。
編輯:為了使這一點更加清楚,當您發現對同一變量使用多個if時,最好使用swicth:
if ($var < 3)
{
// do this
}
elseif ($var < 6)
{
// do that
}
else
{
// do something other
}
這樣寫會更好:
switch ($var)
{
case < 3:
// do this
break;
case < 6:
// do that
break;
default:
// do somehting other
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.