How to use switch/case statements in PHP

switch/case statements are one of my favorite anti-patterns not because I prefer to write spaghetti code but because they can make if/elseif blocks look a ton cleaner. Why would it be considered an anti-pattern? Because it could easily be abused to the point that you are munging up your control structure and basically just writing spaghetti code. Used sparingly, I’m still a fan.

A traditional if/elseif block can look like this:

if ($type == 'first')
{
	// Do first...
}
elseif ($type == 'second')
{
	// Do second...
}
elseif ($type == 'third')
{
	// Do third...
}
elseif ($type == 'fourth')
{
	// Do fourth...
}
else
{
	// Do the rest...
}

As you can see, you’re potentially analyzing the value of $type upwards of 4 times before reaching the final destination of running the else block. If we were to rewrite this as a switch/case statement, it would look more like this:

switch ($type)
{
	case 'first':
		// Do first...
		break

	case 'second':
		// Do second...
		break

	case 'third':
		// Do third...
		break

	case 'fourth':
		// Do fourth...
		break

	default:
		// Do the rest...
		break
}

Speaking in regard to how I format my switch/case statement, it is in fact a few lines longer than the if/elseif blocks (easily remedied by dropping the blank lines, but sacrificing a small bit of readability in my opinion). Length aside, the switch/case does have a bit less typing considering we’re not writing out $type == '...' multiple times and is only analyzing the variable a single time instead of 4 different times.

Even though it’s considered an anti-pattern, I still me love some switch/case statements. Any time I am coding in Python and abusing dictionaries to simulate the same thing I remember why I still love coding in PHP.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.