Programmers Notes

Trick with php switch()

I bet you didn’t know, that switch can be used to answer the question: “Which of the N following statements is true?” Here is how this can be done:

  1. <?php
  2. $a = 1;
  3. $b = 15;
  4. $c = 20;
  5. switch (true)
  6. {
  7.         case $a > $b:
  8.                 {
  9.                         echo ‘$a > $b’;
  10.                         break;
  11.                 }
  12.         case ($a > $b) && ($c > $a):
  13.                 {
  14.                         echo ‘($a > $b) && ($c > $a); $c is the biggest, $b is the lowest’;
  15.                         break;
  16.                 }
  17.         case ($c > $b) && ($c > $a):
  18.                 {
  19.                         echo ‘$c is the biggest again!’;
  20.                         break;
  21.                 }
  22.         default:
  23.                 {
  24.                         echo ‘some default value’;
  25.                         break;
  26.                 }
  27. }
  28. ?>

And little description – you can write true or false in switch(), this will cycle through the case (statement) and execute the commands, that goes below it. In our case, only third statement is true – it prints out, that $c is the biggest.
You shouldn’t use it instead of if or if…elseif…else every time, but if you know this trick, you’ll see when this can be applied.