How to use switch/case statements in PHP

Josh Sherman
2 min read
Software Development 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.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Born again Linux user. Founder of Holiday API, Backend Engineering Manager and Emoji Specialist at Mailshake (WE'RE HIRING!), and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Pears and Perils
Antifragile: Things That Gain from Disorder
Code Girls: The Untold Story of the American Women Code Breakers of World War II

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles