PHP MySQL tutorial

PHP Switch Statement

The PHP switch statement is almost similar to the if elseif else statements.

Syntax

 
switch (expression) {

case label1:

    Block of code // executes if expression = label1;

    break;

case label2:

    Block of code // executes if expression = label2;

    break;

default:

    Block of code // executes if expression value is different from all above labels;
}

The switch statement will execute the expression first and then compare its result with the defined label. If label matches with the expression result then it executes the block of statement defined in the specific label. The break statement will stop the execution of loop and starts the execution of block of code after the switch statement.

In the given below example, firstly current day is calculated. If current day is Sunday or Saturday then it will display the message accordingly. Otherwise, default label will be executed.

<?php
	$KH_CurrentDate = date('d-m-Y');
	$KH_CurrentDay = date("D", strtotime($KH_CurrentDate));
	switch($KH_CurrentDay) {
		case "sun":
			echo "Today is a holiday";
			break;            
		case "sat":
			echo "Today is a half-working day";
			break;
		default:
			echo "Today is a working day";
	}
?>

Download the code Run the code

<<< PHP if elseif else statementsArrays in PHP >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .