PHP Tutorials: Switch Case

In the series of conditional statement, we are now going to learn a next conditional statement Switch-Case it is also called Switch-Case-Default. The Switch Case conditional statement is very similar to the if..elseif..else conditional statement. The only difference you will notice is a syntax.

Syntax:
<?php
	switch (variable) {
		case 'value1':
			# code...
			break;
		case 'value1':
			# code...
			break;
		default:
			# code...
			break;
	}
?>
<?php
	$day = 7;

	switch ($day) {
		case 1:
			echo "Today is Monday.";
			break;
		case 2:
			echo "Today is Tuesday.";
			break;
		case 3:
			echo "Today is Wednesday.";
			break;
		case 4:
			echo "Today is Thursday.";
			break;
		case 5:
			echo "Today is Friday.";
			break;
		case 6:
			echo "Today is Saturday.";
			break;
		default:
			echo "Hurry! Today is Sunday.";
			break;
	}

?>
OUTPUT: Hurry! Today is Sunday.

A Switch Case statement takes a variable as a parameter and checks it against all the cases available inside it. Once a variable value matches with case, it then executes that particular statement. If you notice there is a break; after the statement. It tells the case, where to stop.

Difference between Switch Case and If..elseif..else statement

There is a very basic difference between the Switch Case and if..elseif statement. In if..elseif statement, once the condition matches to true the PHP processor through the control out of if..elseif statement. But in switch case even if it matches the case inside Switch, it keeps executing the statements until it finds a break. That’s why we have used a break after every case. There will be some situation where you will need to skip the break statement and keep educating a few more cases.

Leave a Reply

Your email address will not be published. Required fields are marked *