Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

PHP switch statement


May 10, 2021 PHP


Table of contents


PHP s witch statement

Sometimes, to avoid if statements being too lengthy and to improve the readability of your program, you can use switch branches to control statements.


Switch statements are used to perform different actions based on several different conditions.


PHP switch statement

Use the switch statement if you want to selectively execute one of several blocks of code.

Grammar

switch ( n )
{
case label1:
If n = label1, this code will be executed;
break;
case label2:
If n = label2, this code will be executed;
break;
default:
If n is neither equal to Label1 is not equal to Label2, the code will be executed;
}

How it works: Start by evaluating a simple expression n (usually a variable). C ompare the value of the expression with the value of each case in the structure. I f there is a match, the code associated with the case is executed. A fter the code is executed, use break to prevent the code from jumping into the next case to continue execution. The default statement is used to execute when there is no match (that is, no case is true).

<?php
$favcolor="red";
switch ($favcolor)
{
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, or green!";
}
?>

Run an instance . . .

Tip: Don't miss break when using switch statements, as this may surprise your output.