PHP Tutorial – Switch Statement

Just as the PHP language “if…else” statement, you can use the “switch” statement to alter the flow of a program. In other words; conditional statements are used to perform actions on different conditions. The switch statement is used to select one of many blocks of code to be executed.

Let’s look at a switch example:


<html>
<body>
<?php
	$X=3;
	switch ($X)
	{
		case 1:
			echo “The number is 1”;
		break;
		case 2:
			echo “The number is 2”;
		break;
		case 3:
			echo “The number is 3”;
		break;
		default:
			echo “Non of the numbers match”;
	}
?>
</body>
</html>

We say the variable $X is 3. In the switch statement the blocks of code start with case or default. The case statements end with break. If the value of the case is equal with $X then execute the line between case and break. The break marks the end of one case statement and is used to prevent the code from running into the next case. If non-of the case statement matches with $X then the default code block is executed.

This entry was posted in PHP Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

Comments are closed.