1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 5.00 out of 5)
Loading ... Loading ...

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.

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Share this post with a friend Share this post with a friend

3 Comments

  1. JaneRadriges says:

    I really like your post. Does it copyright protected?

  2. Konstantin Mirin says:

    Yes. You may link to it, but not copy.

  3. CrisBetewsky says:

    Hello! Thanks for the post. It is really amazing! I will definitely share it with my friends.

Leave a Reply