PHP switch Statement

PHP switch statement is used to execute one statement from multiple conditions.it similer to IF statements on the same expression

Syntax

switch ($case) {
    case 0:
        echo "case equals 0";
        break;
    case 1:
        echo "case equals 1";
        break;
    case 2:
        echo "case equals 2";
        break;
}

PHP switch structure with strings

switch ($lang) {
    case "php":
        echo "lang is php";
        break;
    case "mysql":
        echo "lang is mysql";
        break;
}

switch statement execution

The switch statement executes line by line. In the beginning, no code is executed.Only when a case statement is found then it will execute.

$case=0;
switch ($case) {
    case 0:
        echo " case equals 0";
    case 1:
        echo " case equals 1";
    case 2:
        echo " case equals 2";
}
//$case=0; output :case equals 0 case equals 1 case equals 2 
//$case=1; output :case equals 1 case equals 2 

switch statement with break

The statement list case is empty, then paases into the next statement list for the next case.

$case=0;
switch ($case) {
    case 0:
		echo " case equals 0";
    case 1:
        echo " case equals 1";
		break;
    case 2:
        echo " case equals 2";
		break;
}
//$case=0; output :case equals 0 case equals 1
//$case=1; output :case equals 1 

switch statement with default case

The statement list case is empty, then paases into the next statement list for the next case.

$case=5;
switch ($case) {
    case 0:
		echo " case equals 0";
    case 1:
        echo " case equals 1";
		break;
    case 2:
        echo " case equals 2";
		break;
	default:
		echo "default case";
}
//$case=5; output :default case

switch statement can use semicolon(;) instead of colon(:)

switch ($case) {
    case 0;
		echo " case equals 0";
    case 1;
        echo " case equals 1";
}