switch
Оператор switch подобен серии операторов IF с одинаковым условием. Во многих случаях вам может понадобиться сравнивать одну и ту же переменную (или выражение) с множеством различных значений, и выполнять различные участки кода в зависимости от того, какое значение принимает эта переменная (или выражение). Это именно тот случай, для которого удобен оператор switch.
Замечание: Обратите внимание, что в отличие от некоторых других языков, оператор continue применяется в конструкциях switch и действует подобно оператору break. Если у вас конструкция switch находится внутри цикла, и вам необходимо перейти к следующей итерации цикла, используйте continue 2.
Замечание:
Заметьте, что конструкция swich/case использует неточное сравнение (==).
Следующие два примера иллюстрируют два различных способа написать то же самое. Один использует серию операторов if и elseif, а другой — оператор switch:
Пример #1 Оператор switch
if ( $i == 0 ) echo «i равно 0» ;
> elseif ( $i == 1 ) echo «i равно 1» ;
> elseif ( $i == 2 ) echo «i равно 2» ;
>
?php
switch ( $i ) case 0 :
echo «i равно 0» ;
break;
case 1 :
echo «i равно 1» ;
break;
case 2 :
echo «i равно 2» ;
break;
>
?>
Пример #2 Оператор switch допускает сравнение со строками
switch ( $i ) case «яблоко» :
echo «i это яблоко» ;
break;
case «шоколадка» :
echo «i это шоколадка» ;
break;
case «пирог» :
echo «i это пирог» ;
break;
>
?>?php
Важно понять, как оператор switch выполняется, чтобы избежать ошибок. Оператор switch исполняет строчка за строчкой (на самом деле выражение за выражением). В начале никакой код не исполняется. Только в случае нахождения оператора case, значение которого совпадает со значением выражения в операторе switch, PHP начинает исполнять операторы. PHP продолжает исполнять операторы до конца блока switch либо до тех пор, пока не встретит оператор break. Если вы не напишете оператор break в конце секции case, PHP будет продолжать исполнять команды следующей секции case. Например :
switch ( $i ) case 0 :
echo «i равно 0» ;
case 1 :
echo «i равно 1» ;
case 2 :
echo «i равно 2» ;
>
?>?php
В этом примере, если $i равно 0, то PHP исполнит все операторы echo! Если $i равно 1, PHP исполнит два последних оператора echo. Вы получите ожидаемое поведение оператора (‘i равно 2’ будет отображено) только, если $i будет равно 2. Таким образом, важно не забывать об операторах break (даже если вы, возможно, хотите избежать его использования по назначению при определенных обстоятельствах).
В операторе switch выражение вычисляется один раз и этот результат сравнивается с каждым оператором case. В выражении elseif, выражение вычисляется снова. Если ваше условие более сложное, чем простое сравнение и/или находится в цикле, конструкция switch может работать быстрее.
Список операторов для исполнения в секции case также может быть пустым, что просто передает управление списку операторов в следующей секции case.
switch ( $i ) case 0 :
case 1 :
case 2 :
echo «i меньше чем 3, но неотрицательно» ;
break;
case 3 :
echo «i равно 3» ;
>
?>?php
Специальный вид конструкции case — default. Сюда управление попадает тогда, когда не сработал ни один из других операторов case. Например:
switch ( $i ) case 0 :
echo «i равно 0» ;
break;
case 1 :
echo «i равно 1» ;
break;
case 2 :
echo «i равно 2» ;
break;
default:
echo «i не равно 0, 1 или 2» ;
>
?>?php
Выражением в операторе case может быть любое выражение, которое приводится в простой тип, то есть в тип integer, или в тип с плавающей точкой (float), или строку. Массивы или объекты не могут быть здесь использованы до тех пор, пока они не будут разыменованы до простого типа.
Возможен альтернативный синтаксис для управляющей структуры switch. Для более детальной информации, см. Альтернативный синтаксис для управляющих структур.
switch ( $i ):
case 0 :
echo «i равно 0» ;
break;
case 1 :
echo «i равно 1» ;
break;
case 2 :
echo «i равно 2» ;
break;
default:
echo «i не равно to 0, 1 или 2» ;
endswitch;
?>?php
Возможно использование точки с запятой вместо двоеточия после оператора case. К примеру :
switch( $beer )
case ‘tuborg’ ;
case ‘carlsberg’ ;
case ‘heineken’ ;
echo ‘Хороший выбор’ ;
break;
default;
echo ‘Пожалуйста, сделайте новый выбор. ‘ ;
break;
>
?>?php
The PHP switch statement
This post is part of a series of posts about the fundamentals of PHP.
In the previous article we discussed the if statement, where it said you can have many different elseif statements if you wanted to handle many different scenarios, but it gets to a point where you should consider swapping to a switch statement.
$myVar = 'green'; if ($myVar === 'red') echo 'It is red'; > elseif ($myVar === 'blue') echo 'It is blue'; > elseif ($myVar === 'green') echo 'It is green'; >
This can be rewritten using a switch statement. Each condition you want to match has a case where you pass in the variable you want to match. Within the case, you put the code you want to run if the condition matches. Then you need to add a break, otherwise the code will continue to check for matches in the rest of the switch statement.
$myVar = 'green'; switch ($myVar) case 'red': echo 'It is red'; break; case 'blue': echo 'It is blue'; break; case 'green': echo 'It is green'; break; >
Default case
A very useful feature of the switch statement is allowing a default if none of the other cases match. Sometimes you don’t know what the variable will be and it allows you to catch this edge case. You could even use it to throw an exception to deliberately stop any further code running.
$myVar = 'orange'; switch ($myVar) case 'red': echo 'It is red'; break; case 'blue': echo 'It is blue'; break; case 'green': echo 'It is green'; break; default: throw new Exception('It is not a matching colour'); > // Fatal error: Uncaught Exception: It is not a matching colour
Multiple case matching
Sometimes you want to do the same thing for multiple matching cases. If you were to use an if statement you would need to either repeat the code multiple times or use an or ( || ) in your condition.
$myVar = 'green'; if ($myVar === 'red' || $myVar === 'green') echo 'It is red or green'; >
In a switch statement you can do this easily by listing multiple cases one after the other, then adding your code to run with a break after;
$myVar = 'green'; switch ($myVar) case 'red': case 'green': echo 'It is red or green'; break; case 'blue': echo 'It is blue'; break; >
Returning from a switch case
Sometimes you don’t need a break in a switch statement. This is when you directly return from the switch statement. The example below has a switch statement in a function, returning the result from the matching case.
function findTheColour($colour) switch ($colour) case 'red': return 'It is red'; case 'blue': return 'It is blue'; case 'green': return 'It is green'; default: return 'It does not match'; > > echo findTheColour('green'); // It is green
I know that some developers (such as me) think it looks strange not having the breaks in a switch statement as it’s nice to break up the code.
Alternative syntax
As with an if statement, you can also use colons instead of brackets and end the switch with endswitch.
switch ($myVar): case 'red': echo 'It is red'; break; case 'blue': echo 'It is blue'; break; case 'green': echo 'It is green'; break; endswitch;
You can also use semicolons instead of colons after the case if you wanted to.
Using an Array instead
Some people don’t like using switch statements as they can seem a bit verbose. There is a potential alternative using an array to provide the options if it is a simple scenario.
$colours = [ 'red' => 'It is red', 'green' => 'It is green', 'blue' => 'It is blue', ]; $myVar = 'green'; echo $colours[$myVar]; //It is green
The above will work fine for red, green or blue, but if it is an unknown colour, such as orange, then you will end up with an undefined index error.
You could use a null coalescing operator (PHP 7.0 onwards) to catch this error and return a default response.
echo $colours[$myVar] ?? 'It does not match';
Match
PHP 8.0 has introduced the match statement. It offers shorter syntax and it returns a value. There is a great article about the differences between match and switch on stitcher.io by Brent.
Php switch case with return
The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.
Note: Note that unlike some other languages, the continue statement applies to switch and acts similar to break . If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2 .
In the following example, each code block is equivalent. One uses a series of if and elseif statements, and the other a switch statement. In each case, the output is the same.
Example #1 switch structure
switch ( $i ) case 0 :
echo «i equals 0» ;
break;
case 1 :
echo «i equals 1» ;
break;
case 2 :
echo «i equals 2» ;
break;
>
if ( $i == 0 ) echo «i equals 0» ;
> elseif ( $i == 1 ) echo «i equals 1» ;
> elseif ( $i == 2 ) echo «i equals 2» ;
>
?>
It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found whose expression evaluates to a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don’t write a break statement at the end of a case’s statement list, PHP will go on executing the statements of the following case. For example:
switch ( $i ) case 0 :
echo «i equals 0» ;
case 1 :
echo «i equals 1» ;
case 2 :
echo «i equals 2» ;
>
?>?php
Here, if $i is equal to 0, PHP would execute all of the echo statements! If $i is equal to 1, PHP would execute the last two echo statements. You would get the expected behavior (‘i equals 2’ would be displayed) only if $i is equal to 2. Thus, it is important not to forget break statements (even though you may want to avoid supplying them on purpose under certain circumstances).
In a switch statement, the condition is evaluated only once and the result is compared to each case statement. In an elseif statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a switch may be faster.
The statement list for a case can also be empty, which simply passes control into the statement list for the next case.
switch ( $i ) case 0 :
case 1 :
case 2 :
echo «i is less than 3 but not negative» ;
break;
case 3 :
echo «i is 3» ;
>
?>?php
A special case is the default case. This case matches anything that wasn’t matched by the other cases. For example:
switch ( $i ) case 0 :
echo «i equals 0» ;
break;
case 1 :
echo «i equals 1» ;
break;
case 2 :
echo «i equals 2» ;
break;
default:
echo «i is not equal to 0, 1 or 2» ;
>
?>?php
Note: Multiple default cases will raise a E_COMPILE_ERROR error.
Note: Technically the default case may be listed in any order. It will only be used if no other case matches. However, by convention it is best to place it at the end as the last branch.
If no case branch matches, and there is no default branch, then no code will be executed, just as if no if statement was true.
A case value may be given as an expression. However, that expression will be evaluated on its own and then loosely compared with the switch value. That means it cannot be used for complex evaluations of the switch value. For example:
switch ( $target ) case $start — 1 :
print «A» ;
break;
case $start — 2 :
print «B» ;
break;
case $start — 3 :
print «C» ;
break;
case $start — 4 :
print «D» ;
break;
>
For more complex comparisons, the value true may be used as the switch value. Or, alternatively, if — else blocks instead of switch .
switch ( true ) case $start — $offset === 1 :
print «A» ;
break;
case $start — $offset === 2 :
print «B» ;
break;
case $start — $offset === 3 :
print «C» ;
break;
case $start — $offset === 4 :
print «D» ;
break;
>
The alternative syntax for control structures is supported with switches. For more information, see Alternative syntax for control structures.
switch ( $i ):
case 0 :
echo «i equals 0» ;
break;
case 1 :
echo «i equals 1» ;
break;
case 2 :
echo «i equals 2» ;
break;
default:
echo «i is not equal to 0, 1 or 2» ;
endswitch;
?>?php
It’s possible to use a semicolon instead of a colon after a case like:
switch( $beer )
case ‘tuborg’ ;
case ‘carlsberg’ ;
case ‘stella’ ;
case ‘heineken’ ;
echo ‘Good choice’ ;
break;
default;
echo ‘Please make a new selection. ‘ ;
break;
>
?>?php