DEV Community

loading...

PHP hack: Testing for inequality in switch statements

zenulabidin profile image Ali Sherief ・1 min read

I have found another nifty coding device you can use, this time, related to the switch statement.

We all know the switch statement, which looks like:

<?php
switch ($i) {
  case "apple":
    echo "i is apple";
    break;
  case "bar":
    echo "i is bar";
    break;
  case "cake":
    echo "i is cake";
    break;
}
?>
Enter fullscreen mode Exit fullscreen mode

What if you wanted a case where $i is not "apple"? We could put true in the switch expression and put a boolean condition involving $i and "apple" in the case expression, like so:

<?php
switch (true) {
  case ($i != "apple"):
    echo "i is NOT apple";
    break;
  case ($i != "bar"):
    echo "i is NOT bar";
    break;
  case ($i != "cake"):
    echo "i is NOT cake";
    break;
}
?>
Enter fullscreen mode Exit fullscreen mode

We can even mix false testing and true testing in the same switch statement. This device also allows us to test several unrelated variables. For example:

<?php
switch (true) {
  case ($i == "apple"):
    echo "i is apple";
    break;
  case ($i != "bar"):
    echo "i is NOT bar";
    break;
  case ($sqrt > 0.0):
    echo "sqrt result is positive";
    break;
  case (html_entity_decode($_GET["name"]) == "Jon Skeet" &&
        html_entity_decode($_GET["urlslug"]) == "82631"):
    echo "Hooray! Jon Skeet is reading my post!";
    break;
  default:
    echo 'This is equivalent to an else statement.'
    break;
}
?>
Enter fullscreen mode Exit fullscreen mode

In all cases, it's important to leave the switch expression as true. Don't set it to false or any other expression because it will make writing the case expressions inconvenient.

So long, and happy PHPing! 😁

Discussion

pic
Editor guide