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.


    case label1:
        // Code to be executed if n=label1
    case label2:
        // Code to be executed if n=label2

    case label3:
        // Code to be executed if n=label3
        // 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>
	case "Mon":
		echo "Today is Monday.";
	case "Tue":
		echo "Today is Tuesday.";
	case "Wed":
		echo "Today is Wednesday.";
	case "Thr":
		echo "Today is Thursday.";
	case "Fri":
		echo "Today is Friday.";
	case "Sat":
		echo "Today is Saturday.";
	case "Sun":
		echo "Today is Sunday.";
		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.