Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 14 / 68

The switch Statement

In this lesson you will learn PHP's switch statement so you can express branching on a single value more clearly than a chain of if/elseif. This is for anyone searching for "PHP switch statement how to use".

A switch statement is a tidier way to branch on a single value than lining up if / elseif clauses. Do not forget the break.

The sample code prints a day name based on $day. It matches case 3:, so "Wednesday" is printed, and the following break leaves the switch. default handles the case where nothing matched.

The single biggest stumbling block for beginners is forgetting break. Without it, execution runs straight on from the matching case into the next one - a phenomenon called fall-through, and a ready source of bugs.

It keeps branches with many options readable and is a frequently used construct in practice. PHP 8 and later also added the match expression, which is even more concise.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)