2

The variable:

$mask = A | B | C;

And I can use switch to test each constant like this:

switch(true){
  case $mask & A:
   ...
  case $mask & B:
   ...
  case $mask & C:
   ...
}

I was wondering if it's possible to have a nicer switch, like:

switch($mask){
  case A:
   ...
  case B:
   ...
  case C:
   ...
}

I believe I need to modify the variable somehow with the weird ~ operator thing. but how?

Alex
  • 66,732
  • 177
  • 439
  • 641

1 Answers1

1

It is possible to structure a switch as you stated

<?php

define("A", 1);
define("B", 2);
define("C", 4);


$mask = B | C;

switch(true){
  case $mask & A:
    echo "A";
    break;
  case $mask & B:
    echo "B";
    break;
  case $mask & C:
    echo "C";
    break;
}
?>

But the problem is a switch will only trigger the first matching condition. So the above code with $mask = B | C; will only echo B when you probably want it to echo BC

So in short if you want the behavior to be that it executes only the first matching condition then you can use this otherwise you will have to do a series of ifs.

Orangepill
  • 24,500
  • 3
  • 42
  • 63