Home > Tutorials > PHP Tutorials > The PHP Switch Conditional Statement

The PHP Switch Conditional Statement

The switch statement allows you to simplify our previously written if…elseif…else statement by not constantly writing out the condition to check for. So, let’s take our code:

<?php
$name = "Eric";

if ($name == "Mike") 
	{
		echo "Name Is Mike B.";
	} elseif ($name == "Eric")  {
		echo "Name is Eric A.";
	} elseif ($name == "JD")  {
		echo "Name is JD M.";
	} else {
		echo "Name is $name";
		}
?>

And rewrite it in the form of a switch statement.

<?php
$name = "Eric";

switch ($name) {
  case "Mike":
    echo "Name Is Mike B.";
    break;
  case "Eric":
    echo "Name is Eric A.";
    break;
  case "JD":
    echo "Name is JD M.";
    break;
  default:
    echo "Name is $name";
}
?>

This is how it works: First we have a single expression n (a variable in our case called $name), that is evaluated once. The value of the expression is then compared with the values for each case in our switch statement. If there is a match, the block of code associated with that case is executed. If no match is found the default statement is used. break; is used to separate the various case types.

About Michael Boguslavskiy

Michael Boguslavskiy is a full-stack developer & online presence consultant based out of New York City. He's been offering freelance marketing & development services for over a decade. He currently manages Rapid Purple - and online webmaster resources center; and Media Explode - a full service marketing agency.

Check Also

5 Must Have WordPress Optimization Plugins For A Fast Loading Website

Having a fast loading website is essential these days. First off, users are impatient. If ...

Like every other website, this site uses cookies to analyze our traffic. Cookies may also be utilized by our advertisers and partners. By using this website you agree to the use of said cookies. More Information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings, continuing to navigate past this message, or you click "Accept" below then you are consenting to the use of cookies on the Rapid Purple website.

Close