PHP Conditional Statements: if else, switch

PHP Conditional Statements: if else, switch
5 (100%) 1 vote

If statement

Execute the code if the condition is true

If…else statement

Switch statement

Execute different code depending on a condition.
The switch statement is similar to a series of IF statements

switch ($var) {
    case value1:
        code will be executed if $var matches the value1;
        break;
    case value2:
        code will be executed if $var matches the value2;
        break;
    case value3:
    case value4:
        code will be executed if $var matches the value3 or the value4;
        break;
    ...
    default:
        do this if nothing else matches;
} 

If the value pass to the switch statement matches, the code that follows the case is executed.

Example:
	$degrees = "23";
	switch($degrees){
		case ($degrees < 10):
			echo "it's very cold outside";
			break;
		case ((10 <= $degrees) && ($degrees < 20)):
			echo "it's cold outside";
			break;
		case ((20 <= $degrees) && ($degrees < 30)):
			echo "it's nice outside";
			break;
		case ((30 <= $degrees) && ($degrees < 40)):
			echo "it's hot outside";
			break;	
		case ((40 <= $degrees) && ($degrees < 45)):
			echo "it's very hot outside";
			break;		
		default:	
			echo "I do not know what it's like outside";
	} //The result: it's nice outside

Be careful! if we forget to put break, the code after “case” it will run even if will not match the value!!!

Example:
	$degrees = "23";
	switch($degrees){
		case ($degrees < 10):
			echo "it's very cold outside ";
			break;
		case ((10 <= $degrees) && ($degrees < 20)):
			echo "it's cold outside ";
			break;
		case ((20 <= $degrees) && ($degrees < 30)):
			echo "it's nice outside ";
		case ((30 <= $degrees) && ($degrees < 40)):
			echo "it's hot outside ";
			break;	
		case ((40 <= $degrees) && ($degrees < 45)):
			echo "it's very hot outside ";
			break;		
		default:	
			echo "I do not know what it's like outside";
	} //The result: it's nice outside it's hot outside

Leave a Reply

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