PHP switch case more than one value in the case
Asked Answered
C

6

58

I have a variable that holds the values 'Weekly', 'Monthly', 'Quarterly', and 'Annual', and I have another variable that holds the values from 1 to 10.

switch ($var2) {
    case 1:
        $var3 = 'Weekly';
        break;
    case 2:
        $var3 = 'Weekly';
        break;
    case 3:
        $var3 = 'Monthly';
        break;
    case 4:
        $var3 = 'Quarterly';
        break;
    case 5:
        $var3 = 'Quarterly';
        break;
    // etc.
}

It isn't beautiful, because my code has a lot of duplicates. What I want:

switch ($var2) {
    case 1, 2:
        $var3 = 'Weekly';
        break;
    case 3:
        $var3 = 'Monthly';
        break;
    case 4, 5:
        $var3 = 'Quarterly';
        break;
}

How can I do it in PHP?

Coburg answered 12/11, 2010 at 9:29 Comment(1)
Where does the 1 through 10 logic come into play??? I find this question to be Unclear. is this question a duplicate of PHP: two values in the case of Switch??Commeasure
D
137

The simplest and probably the best way performance-wise would be:

switch ($var2) {
    case 1:
    case 2:
       $var3 = 'Weekly';
       break;
    case 3:
       $var3 = 'Monthly';
       break;
    case 4:
    case 5:
       $var3 = 'Quarterly';
       break;
}

Also, possible for more complex situations:

switch ($var2) {
    case ($var2 == 1 || $var2 == 2):
        $var3 = 'Weekly';
        break;
    case 3:
        $var3 = 'Monthly';
        break;
    case ($var2 == 4 || $var2 == 5):
        $var3 = 'Quarterly';
        break;
}

In this scenario, $var2 must be set and can not be null or 0

Dimension answered 12/11, 2010 at 9:31 Comment(4)
($var2 == 1 || $var2 == 2) may not work correctly depending on what $var2 is. If $var2 = 0 the first case will be executed. It's also a lot more verbose than the plain case style. You're also breaking a little too often.Abomasum
@deceze, agreed, thats why i put the other solution first, its just an example for "complex" boolean comparisonDimension
If you were to use this style at all, at least do it correctly by making the condition work correctly: switch (true) { case ($a || $b) : ... }Abomasum
@Abomasum if were to do that then case 3 would no longer work, but i will ad a noteDimension
A
12
switch ($var2) {
       case 1 :
       case 2 :
          $var3 = 'Weekly';
          break;
       case 3 :
          $var3 = 'Monthly';
          break;
       case 4 :
       case 5 :
          $var3 = 'Quarterly';
          break;
}

Everything after the first matching case will be executed until a break statement is found. So it just falls through to the next case, which allows you to "group" cases.

Abomasum answered 12/11, 2010 at 9:32 Comment(0)
K
4

If You're reading this and the year is 2021 and beyond, You're also using PHP > 8.0, you can now use the new match expression for this.

this could be

$var3 = match($var2){
    1, 2    => 'Weekly',
    3       => 'Monthly',
    4, 5    => 'Quarterly',
    default => 'Annually',
};

Please note that match does identity checks, this is the same as === compared to switch equality check which is ==.

read more about match expression here

Katrinka answered 29/4, 2021 at 2:12 Comment(0)
T
1

Switch is also very handy for A/B testing. Here is the code for randomly testing four different versions of something:

$abctest = mt_rand(1, 1000);
switch ($abctest) {
    case ($abctest < 250):
        echo "A code here";
        break;
    case ($abctest < 500):
        echo "B code here";
        break;
    case ($abctest < 750):
        echo "C code here";
        break;
    default:
        echo "D code here";
        break;
Towe answered 3/2, 2014 at 11:5 Comment(1)
Congratulate you with your first answer! But it's offtop :)Coburg
S
0

You could use array to store you match groups; like:

    <?php
    $names = array('Ian', 'Jack', 'Fred', 'Ismail');
    $name = 'Vladimir';
    switch ($name) {
    case (in_array($name, $names)):
            echo '<p> Welcome ' . $name . '</p>';
            break;
        default:
            echo '<p>' . $name . ' is a stranger to me?</p>';
    }
?>
Supposing answered 25/1, 2021 at 21:34 Comment(0)
B
0
function bankRemark()
{
    
    $this->db->select('id,status,funding_dt,date,remarks1');
    $this->db->from($this->db_sdip);       
    $this->db->where("amc_remark != '' ");      


    $query = $this->db->get();  

    // echo $this->db->last_query();die;

    if($query->num_rows() > 0)
    {
        $data = $query->result();    
        foreach($data as $val)
        {
            $id         = $val->id;
            $status     = strtoupper($val->status);
            $funding_dt = $val->funding_dt;
            $date       = $val->date;
            $remarks1   = $val->remarks1;

            switch ($favcolor) {
                case "REFUND":
                case "STALE":
                    if(date("d-m-Y",strtotime($funding_dt)) >= date("d-m-Y",strtotime('31-01-2007')))
                    {
                        $this->db->where('id', $id);
                        $this->db->update($this->db_sdip, array(
                            'remarks1 '     => 'Rejected',
                            'amc_remark'    => 'Check in FD'
                        ));  
                    }

                    if( (date("d-m-Y",strtotime($funding_dt)) >= date("d-m-Y",strtotime('01-05-2003'))) and (date("d-m-Y",strtotime($funding_dt)) <= date("d-m-Y",strtotime('31-01-2007'))))
                    {
                       if($remarks1 = '')
                       {
                            $this->db->where('id', $id);
                            $this->db->update($this->db_sdip, array(
                                'remarks1 '     => 'Approved',
                                'amc_remark'    => 'Office Note Dated '.date('d-m-Y')
                            ));  
                       }else{
                            $this->db->where('id', $id);
                            $this->db->update($this->db_sdip, array(
                                'remarks1 '     => 'Rejected',
                                'amc_remark'    => 'Wrong Funding Date'
                            ));  
                       }
                    }
                  break;              
                default:
                  echo "Invalid Input";
              }
     
        }

       
    }
    else
    {
        return NULL;
    }
}
Bridegroom answered 11/12, 2021 at 6:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.