Creative Switching

The switch statement is one of the basic control structures in PHP and many other languages. At its simplest it can be used to quickly ‘choose’ between a series of different values but with a little imagination it can do much more than that. I find it extremely easy to read code using a switch statement, which is one of the reasons I like using it so much. In this post I’m going to give a few examples of some of the useful things you can do with a switch statement in your code but to begin with I’ll explain an important point that could trip people up

Remember: Loose Comparison

When using a switch statement the most important thing to remember is that comparisons with the value following the switch keyword are done in a loose fashion. It’s the equivalent of using the equality (==) operator instead of the identity (===) operator. Consider the following code:


switch (true) {

case 1:

echo '1 == true in PHP';

}

This will write out the string ‘1 == true in PHP’. Hopefully why this is important will become apparent in a moment.

Making Your Code More Readable

For me one of the main things I use a switch statement for is to replace long if..else if..else if..else statements. This is done by making the switch statement compare against a value of true and making each of the case statements evaluate one or more conditions that return a boolean value. Here’s an example:


$a = 'This is a string';

switch (true) {

case (is_string($a) && strlen($a) < 100):

echo '$a is a string and is less than 100 characters long';

break;

case (is_int($a) && $a < 100):

echo '$a is an integer which is less than 100';

break;

default:

echo '$a is neither a string of less than 100 characters or an integer of less than 100';

}

This code will obviously always use the first case statement but the important thing is in what’s going on. By making each case statement evaluate one or more expressions that return a boolean value it’s possible to take a course of action depending on the value of a variable. Of course this is possible using if..else if.. but I personally find the use of a switch statement much clearer and easier to read. The caveat here, as mentioned above, is that the expressions following the case statements must return a boolean value. If they return a value which can be evaluated as a boolean in a loose comparison some weird things might occur.

Sanity Checking

Where this technique can really come into it’s own is in sanity checking one or more values passed to a method or function. I often use a switch statement in __get() or __set() methods to perform sanity checks on the values passed to the methods. Consider the following simple example:


class foo {

 protected $integer = 1;

 protected $string = '';

 protected $array = array();

 public function __get($name) {
 switch (true) {
 //Perform sanity checks on the name variable and the current values held in the object
 case ($name === 'integer' && $this->integer):
 case ($name === 'string' && strlen($this->string)):
 case ($name === 'array' && count($this->array)):
 return $this->$name;
 default:
 //None of the conditions above met. Return false.
 return false;
 }
 }

 public function __set($name, $value) {
 switch (true) {
 //Perform sanity checks on the name and value passed
 case ($name === 'integer' && is_int($value)):
 case ($name === 'string' && is_string($value)):
 case ($name === 'array' && is_array($value)):
 $this->$name = $value;
 return true;
 default:
 return false;
 }
 }
 }

This code defines a setter and getter for protected or private values in an object. Using the switch statements it’s very easy to perform sanity checking on the values passed to the methods and, in the case of the getter, even the values held by the properties of the object. It would also be very easy to add further case statements to either of these methods if more protected or private properties were added to the class. Contrast this to using if..else if: the code would be less readable and harder to make changes to.

Omitting the Break

Another feature of the switch statement in PHP is that once a case statement has been matched all of the statements following further case’s are executed until a break or continue statement is reached. This behaviour can be used to perform actions on a value passed to a function or method. Have a look at this very simple example:


public function stringFunc ($string) {
 switch (true) {
 case (! is_string($string)):
 throw new InvalidArgumentException('$string must be a string');
 case (strlen($string) > 100):
 $string = substr($string, 0, 100) . '...';
 default:
 $string = strtolower($string);
 }
 //Do something with $string
 }

This simple example performs a sanity check on an argument passed to a method and then does some basic formatting on the value. The important thing here is the absense of any break statements. If a string of more than 100 characters is passed to the method it is truncated by the second case statement. Because there is no break the code following the default statement is executed, lowercasing the string. If a string of less than 100 characters is passed the default statement is executed, simply lower casing the string. Doing this without the switch statement would take three separate if statements and be much harder to read. The switch statement is also easier to maintain: if you want to introduce some extra processing based on the value simply add another case statement.

Conclusion

I hope that some of you have found this post to be useful. Is this a technique that many other people are using? If so how do you use switch statements? Post comments below as I’d love to know how others are using this control structure in PHP.

2 thoughts on “Creative Switching

  1. As a C# Developer I tend to Abstract my code away from if conditions, I rarely get into a situation where I am writing more than an if…else scenario.

    I have however seen a few posts that use this methodology and I do think that it is very interesting, and quite readable. I tend to use switch statements for enumeration flags, or like you said multiple conditions that require the same functionality.

    Excellent post, keep up the good work!

    Cory

    1. Thanks Cory! I’m interested in techniques that you might use in C# that could also be applied to PHP, since the syntax is somewhat similiar. Are there other ways that you might use switch statements in C# that could also be applied to PHP?

Leave a Reply