Get DevWP - WordPress Development Theme

PHP Switch Statement

In the last article, I demonstrated how to use PHP’s if elseif and else control structures for decision making. PHP also supports Switch Statements which in some cases might be ideal and easier to follow once you grasp how it works.

In this article I will show you how to implement Switch Statements in PHP as an alternative to the standard if elseif else method.

Just like the if statement, switch statements are used to perform different actions based on different scenarios or conditions.

Below is an example of a Switch Statement in action.



<?php
$color = "blue";

switch ( $color ) {
	case "purple":
		echo "Your color is purple";
		break;
	case "green":
		echo "Your color is green";
		break;
	case "black":
		echo "Your color is black";
		break;
	case "blue":
		echo "Your color is blue";
		break;
	default:
		echo "I can't figure out your color";
}
?>

Let’s Breakdown the Code

  • First you will notice that we have a variable with it’s value $color = "blue";
  • then we open up with the word switch followed by a pair of parenthesis and $color is inside those parenthesis which is the condition we are testing for
  • then we have our opening { brace
  • then we have the case “purple”: which is checking if purple matches the colors value
  • if it matches the color purple, it then echo "Your color is purple"; followed by break;
  • if it doesn’t match the color purple, then it moves onto the next test for green and so on until it finds the correct color match.
  • if none of the case’s match, then it moves to the default: echo “I can’t figure out your color”;
  • then the closing }

PHP if elseif else vs Switch

Let’s compare the switch statement from above with it’s equivalent if elseif else statement.



<?php
$color = "blue";
if ( $color == "purple" ) {
	echo "Your color is purple";
} elseif ( $color == "green" ) {
	echo "Your color is green";
} elseif ( $color == "black" ) {
	echo "Your color is black";
} elseif ( $color == "blue" ) {
	echo "Your color is blue";
} else {
	echo "I can't figure out your color";
}
?>

The end result might be the same but in some cases, a switch statement might be ideal, especially when dealing with long conditional statements.

The Takeaway

PHP offers more than one way to implement control structures. Copy the code in this tutorial and play around with it locally. The best way to learn how to code is to actually code.



View Our Themes