PHP Switch Statements

PHP Switch Statements

·

2 min read

In this tutorial, we will be learning about the switch statement.

The switch statement is a condition that causes different things to happen depending on the value of a variable.

While it may look simple, there are a few tricky points you must be careful of.

Syntax

<?php
switch($x)
{
Case 1:
//php code...
break;
Case 2:
//php code...
break;
Case 3:
//php code
break;
}
?>

You can think of a switch statement involving $x as the following: check the value of $x, if $x equals to case 1 execute the code below case 1.

If $x equals to case 2, then execute the code below case 2.

At first glance, this doesn’t sound that different from a series of if-else statements.

Yet there are some subtle and tricky differences between the two.

The first difference is that for all the cases of $x, you can only have one value.

You can only say if $x == ?. You cannot go if $x<=? And $x<=? or $x<100.

If you need to check whether $x falls between a certain range of value, then you should use if-else statements.

The next part is even more important:

When you look at a typical switch statement, you will see a break at the end of every block of code. It will say case 1, break and then case 2.

For an if-else statement, it wasn’t necessary to add any break in every section.

However, the switch statement works differently.

This is a point that a lot of people get wrong: what happens in a switch statement is that it checks the value of your variable and sees which case it matches. Once it’s picked the correct case, all the code below it will execute.

The code does not stop executing code just because you are at the end of a particular case block. To stop further execution of the switch statement, you must add a break.