PHP Switch Statement

The switch statement in PHP is used to execute a single statement based on a set of multiple conditions. It’s similar to a PHP if-else-if statement.

Syntax:

switch(n){
    case label1:
        // Code to be executed if n=label1
        break;
    case label2:
        // Code to be executed if n=label2
        break;

    case label3:
        // Code to be executed if n=label3
        break;
    ...
    default:
        // Code to be executed if n is different from all labels
}

PHP Switch Statement Working:

We begin with a single expression n (usually a variable) that is evaluated only once.

The value of the expression is then compared to the values in the structure for each case. If a match is found, the code block associated with that case is run. Break the code to prevent it from automatically moving on to the next case. If no match is found, the default statement is used.

<h2>Switch Statement Example</h2>
<?php
$day=date("D");
switch($day){
	case "Mon":
		echo "Today is Monday.";
		break;
	case "Tue":
		echo "Today is Tuesday.";
		break;
	case "Wed":
		echo "Today is Wednesday.";
		break;
	case "Thr":
		echo "Today is Thursday.";
		break;
	case "Fri":
		echo "Today is Friday.";
		break;
	case "Sat":
		echo "Today is Saturday.";
		break;
	case "Sun":
		echo "Today is Sunday.";
		break;
	default:
		echo "You entered wrong case!";
	
}
?>
Important points about PHP Switch Statement:
  • Default is an optional statement. Even if it doesn’t matter, but the default statement should always be the last statement.
  • In a switch statement, there can only be one default. A fatal error can occur if more than one default is used.
  • A break statement can be added to each case to end the sequence of statements.
  • In switch, the break statement is optional. If no break is given, all statements will run after finding a case value that matches.
  • Switch statements can be nested, but this makes the code more complex and difficult to read.
  • In a switch expression, PHP allows you to use number, character, string, and functions.
  • You can use a semicolon (;) instead of a colon (:). It will not generate any error.