11 Vote

PHP switch/case: Condition with multiple Values

Question by PC Control | 2015-02-10 at 21:53

I would like to program a SWITCH statement using PHP in which several values should lead to the same condition.

Up to now, I have tried the following variations:

// VARIANT 1 - not working
switch($v) {
  case 0, 1, 2: echo 'A'; break;
  case 3:       echo 'B'; break;
}

// VARIANT 2 - not working
switch($v) {
  case 0 || 1 || 2: echo 'A'; break;
  case 3:           echo 'B'; break;
}

The first way is resulting in an error message, the second way always leads to executing condition "A" and I do not know why.

Of course, one solution to solve the problem is to just copy of the whole first three cases, but I think, this is not very elegant.

Is there any simpler solution or is something like this not provided in PHP?

ReplyPositiveNegative
Avatar
1Best Answer1 Vote

PHP provides something for that.

You can just implement your plan in the following way:

switch($v) {
  case 0: 
  case 1: 
  case 2:   echo 'A'; break;
  case 3:   echo 'B'; break;
}

After one CASE is met, PHP is going on until there is a BREAK. You can use this behavior here with writing several CASES after each other.
2015-02-11 at 13:56

ReplyPositive Negative
Reply

Related Topics

MySQL: IF-Condition with OR

Question | 1 Answer

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.