Switch Case in PHP: A Small Code Example

Quick Summary

  • A PHP switch compares one value against a list of cases and runs the first match, a tidier option than long if/elseif chains.
  • End each case with break to avoid fall-through, and use the optional default case for values that match nothing.
  • Cases use loose comparison, not strict, which matters when switching on strings that start with a number.

A switch case in PHP compares one value against a list of cases and runs the code of the first one that matches. It’s a tidier alternative to a long if/elseif chain when you check the same variable again and again.

The basic syntax

PHP
switch (variable) {
	case 'value':
		# code...
		break;
	
	default:
		# code...
		break;
}

Replace variable with the value you want to test and 'value' with what to compare it against. Add as many case blocks as you need.

  • Each case is compared with loose comparison (==), not strict comparison (===). That matters when you switch on strings that start with a number.
  • break ends the switch. Without it, PHP keeps running the code of the following cases as well, which is called fall-through.
  • default runs when no case matches. It’s optional.

Example: even or odd

PHP
$n = 12;
$r = $n % 2;

switch ($r) {
	case 0:
		echo "{$n} is an even number \n";
		break;
	default:
		echo "{$n} is an odd number";
		break;
}

$n % 2 gives the remainder of dividing $n by 2. A remainder of 0 means the number is even; any other value is handled by default, which reports an odd number. With $n = 12 it prints 12 is an even number. The curly braces in "{$n} is an even number" insert the variable into the double-quoted string. Single-quoted strings don’t do this, as the PHP string basics show.

Example: a message for each day

PHP
switch (date('l')) {
	case "Monday":
		echo "PHP on Monday";
		break;
	case "Tuesday":
		echo "Angular on Tuesday";
		break;
	case "Wednesday":
		echo "Python on Wednesday";
		break;
	case "Thursday":
		echo "Node on Thursday";
		break;
	case "Friday":
		echo "Laravel on Friday";
		break;
	case "Saturday":
		echo "WordPress on Saturday";
		break;
	case "Sunday":
		echo "React js on Sunday";
		break;
	default:
		echo "I don't know what day it is";
		break;
 }

date('l') returns the full English name of the current weekday, such as Monday, based on PHP’s default timezone setting. The switch prints a different message for each of the seven days. Because date('l') always returns one of those names, the default case is only a safety net here.

Share on X (opens in a new tab) Share on LinkedIn (opens in a new tab) Share on Facebook (opens in a new tab)

ChatGPT (opens in a new tab) Claude (opens in a new tab) Gemini (opens in a new tab) Perplexity (opens in a new tab) Grok (opens in a new tab)

More Insights

See More