Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 4.4Switch statements in PHP

Part 4.4Switch statements in PHP

This article is continuing with conditional statements with the switch (case) statement. In other languages, such as VB.NET, switch statements are known as case statements, but in the C family of languages, from which PHP takes inspiration, they are referred to as switch statements.

Switch

Think about a switch. In this case, the switch will turn on the alarm system in a house.

With an alarm system a single press of the button (≤ 1 second press) will start the alarm in 15 seconds. A hold press (≤ 3 second press) enables the alarm in 5 minutes. Finally, double pressing the alarm (two single presses with a ≤ 1 second delay between them) will disable the alarm.

This could be converted to an if statement with many else if statements. However, to make it more efficient, a switch statement could be used.

In a realistic PHP example, there could be two variables being compared. The user wants to know whether or not they are able to get the number 1 or not from a sample. This can be achieved using an if statement that utilises the elseif statement.

PHP
<?php
	//Simple if statement with elseif
	$test1 = 5;
	if($test1 == 0) {
		echo "There's nothing";
	}
	elseif($test1 == 1) {
		echo "It is now 1";
	}
	else {
		echo "It's not one or zero";
	}
?>
		
It's wrong

This solution is cumbersome and can be made more concise with a switch statement.

PHP
<?php
	//Simple switch statement for comparison to if statement
	$test1 = 5;
	switch ($test1)
	{
		case 0:
			echo "There's nothing";
			break;
		case 1:
			echo "It is now 1";
			break;
		default:
			echo "It is not one or zero";
	}
?>
		
It is wrong

Whilst this solution is technically a line shorter per condition, it has a much nicer structure than with an else/if system. Case can be useful in all different ways - especially as the statements get larger.

Feedback 👍
Comments are sent via email to me.