Jump to: navigation, search

Php switch

From w3cyberlearnings

Contents

switch

switch is similar to if-else-if-else condition. When the switch case statement matches the value of the switch expression, then it begins to executed the statements and it will executes until it sees a break statement. Without a break statement, the case statement continues to match the switch expression until a case's statement list or when it's finally reach the default statement. The switch statement is faster and clearer than the If/ElseIf/Else statement.

Syntax

switch (expr) {
  case value1 :
      statement
      break;
  case value2 :
      statement 
      break;
  case value3 :
      statement
      break;
  case value4 :
      statement
      break;
  default:
      statement
      break;
}

Example 1

<?php

$i = 4;

switch ($i) {
	case 1:
		echo 'One';
		break;
	case 2:
		echo 'Two';
		break;
	case 3:
		echo 'Three';
		break;
	case 4:
		echo 'Four';
		break;
	default:
		echo 'default';
		break;
}
?>

Output

Four 

Example 2

<?php

$choice = 'beer';

switch ($choice) {
	case 'beer':
	case 'patron':
	case 'bug light':
		echo 'good choice';
		break;
	case 'mix drink':
		echo 'nothing much';
		break;
	case 'cocacola':
		echo 'just a drink';
		break;
	default:
		echo 'water';
		break;
}
?>

Output

good choice

Example 3

<?php

$person_op = array(
	 array('john', 'patron'),
	 array('mark', 'bug light'),
	 array('paul', 'mix drink'),
	 array('marry', 'cocacola'),
	 array('janny', 'do not drink')
);


foreach ($person_op as $person) {
	echo $person[0];
	echo ' select ';
	echo u_option($person[1]);
	echo '<br/>';
}

function u_option($choice) {
	switch ($choice) {
		case 'beer':
		case 'patron':
		case 'bug light':
			echo 'good choice';
			break;
		case 'mix drink':
			echo 'nothing much';
			break;
		case 'cocacola':
			echo 'just a drink';
			break;
		default:
			echo 'water';
			break;
	}
}

?>

Output

john select good choice
mark select good choice
paul select nothing much
marry select just a drink
janny select water

Related Links


Navigation
Web
SQL
MISC
References