简体   繁体   中英

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:

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 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. You have to realize the the switch statement only accepts one parameter:

switch($arg)

In your case you have amount as $_POST["amount"] and fruit as $_POST["fruit"] . Your first problem is how will you pass that 2 values on the switch statement.

You cannot use a switch for this case, since you are checking a condition ( isset ) of two variables which produces a boolean result. 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. 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.

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 ($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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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