简体   繁体   English

IF vs. SWITCH,哪个更适合这项工作?为什么?

[英]IF vs. SWITCH and which is more suitable for this job and why?

I'm wondering whether it is possible to replicate this kind of check in a switch statement/case: 我想知道是否有可能在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

Note: I'm paying more attention to the && comparison that can be done simply in one IF, and whether this is possible to be done in a switch case and receive results like the nested if/else would. 注意:我将更加关注可以在一个IF中简单完成的&&比较,以及是否有可能在切换情况下完成并接收嵌套if / else这样的结果。 If it's not possible, why? 如果不可能,为什么呢? and which method would be more efficient and why? 哪种方法更有效?为什么?

I would rather stick with If-Else If condition rather than converting it to Switch statement. 我宁愿使用If-Else If条件,也不愿将其转换为Switch语句。 You have to realize the the switch statement only accepts one parameter: 您必须认识到switch语句仅接受一个参数:

switch($arg)

In your case you have amount as $_POST["amount"] and fruit as $_POST["fruit"] . 在您的情况下, amount$_POST["amount"]fruit$_POST["fruit"] Your first problem is how will you pass that 2 values on the switch statement. 您的第一个问题是如何在switch语句中传递这2个值。

You cannot use a switch for this case, since you are checking a condition ( isset ) of two variables which produces a boolean result. 在这种情况下,您不能使用开关,因为您正在检查两个产生boolean结果的变量的条件( isset )。 Well actually you could do a switch of this condition and switch in case of true to this code and in case of false to that code. 那么实际上你可以做一个switch这个条件,并在真实的情况下,切换到该代码,并在假到代码的情况。 But that would not make much sense imho. 但是,恕我直言,这没有多大意义。 In a switch you can just check ONE variable or expression and in the cases you execute the code of whatever the result of that switch evaluation was. 在开关中,您只需要检查一个变量或表达式,就可以执行无论该开关求值结果如何的代码。 So no, you cannot do a switch with these nested ifs. 因此,不能,您不能使用这些嵌套的if进行切换。

edit: to make this a bit more clear, a swicth is best used when you find yourself using multiple ifs on the same variable: 编辑:为了使这一点更加清楚,当您发现对同一变量使用多个if时,最好使用swicth:

if ($var < 3)
{
    // do this
}
elseif ($var < 6)
{
    // do that
}
else
{
   // do something other
}

Would be much better written: 这样写会更好:

switch ($var)
{
    case < 3:
        // do this
        break;
    case < 6:
        // do that
        break;
    default:
        // do somehting other
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM