Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using comparison operators in a PHP 'switch' statement

I have four conditions that I need to go through and I thought it would be best to use the switch statement in PHP. However, I need to check whether an integer is, let's say, less than or equal, or greater than and equal.

switch ($count) {     case 20:         $priority = 'low';         break;      case 40:         $priority = 'medium';         break;      case 60:         $priority = 'high';         break;      case 80:         $priority = 'severe';         break; } 

With an if() statement it would look like the following:

if ($count <= 20) {     $priority = 'low'; } elseif ($count <= 40) {     $priority = 'medium'; } elseif ($count <= 60) {     $priority = 'high'; } else {     $priority = 'severe'; } 

Is that possible in switch-case?

like image 260
Jessie Stalk Avatar asked Jul 17 '14 20:07

Jessie Stalk


People also ask

Can you do comparisons in a switch statement?

So no. Remember, your case expressions (if they're things like x>y ) evaluate to a boolean value. That's right, just a boolean value. Anyway it's just an answer for your question, switch(true) is not a good approach.

Can I use operators in switch statement?

No you can not.

Does PHP have a switch statement?

The PHP switch Statement Use the switch statement to select one of many blocks of code to be executed.


2 Answers

A more general case for solving this problem is:

switch (true) {     case $count <= 20:         $priority = 'low';         break;      case $count <= 40:         $priority = 'medium';         break;      case $count <= 60:         $priority = 'high';         break;      default:         $priority = 'severe';         break; } 
like image 188
Konr Ness Avatar answered Oct 01 '22 11:10

Konr Ness


Switches can't do that, but in this particular case you can do something like this:

switch ((int)(($count - 1) / 20)) {     case 0:         $priority = 'low';         break;     case 1:         $priority = 'medium';         break;     case 2:         $priority = 'high';         break;     case 3:         $priority = 'severe';         break; } 

So in (int)(($count - 1) / 20) all values from 0 to 20 will eval to 0, 21 to 40 will eval to 1 and so on, allowing you to use the switch statement for this purpose.

And since we are concatenating values, we can even simplify to an array:

$priorities = ['low', 'medium', 'high', 'severe']; $priority = $priorities[(int)(($count - 1) / 20)]; 
like image 25
Havenard Avatar answered Oct 01 '22 10:10

Havenard