Let’s see step by step the last of the conditional control structures, a different conditional for different problems that often achieves greater code organization and speed.
In this tutorial you will learn the following key concepts to learn how to use SWITCH in PHP:
- Using the control structure switch in php.
- What is it for and how is the sentence used? case PHP.
- The default case of a switch.
- Using the php switch statement advancing.
- How to use conditions in a php switch or what is the same, how to convert a switch into a kind of IF .
Content
- Conditional control structures php. The Switch
- Cases of a php switch
- SWITCH and CASE flowchart
- IF code equivalent to SWITCH PHP
- The default statement in switch
- The switch without break in php
- Advanced switch or with conditions
- Knowledge to better understand a PHP Switch
Conditional control structures php. The Switch
The Switch conditional statement is the same as the conditionals IF, IF ELSE and IF ELSEIF, that is, a conditional control structure: it will depend on a condition to execute a series of lines. But in the switch case, this condition is about a value. Thus, the switch will always depend on a variable, and on all the values that it can take.
The basic sentence in PHP Switch is like the following example:
<?php switch ( $variable ) { } ?>
As you can see, the syntax, that is, how I write the statement, is similar to that of an if, but in this case a comparison is not made, nor is it sought to make the result of the comparison true. It only takes into account what value the variable takes.
Cases of a php switch
To deal with the different possible values that we foresee that the switch variable can take, we will establish a series of cases or case, these cases will contemplate a specific value (numeric, text, boolean, etc) and if it matches that of the variable, they will execute the code they contain.
Let’s see a php switch example:
<?php switch ( $numero ) { case 1: echo '$numero vale 1'; break; case 2: echo '$numero vale 2'; break; } ?>
In this PHP example I have shown you a complete basic switch, in which I treat the value cases 1 or 2 for the variable $number. If the value of the variable is 1, the code that follows the colon will be executed (echo ‘$number is 1’) until the break is executed, a statement that ends the code reading on the switch.
As its name indicates the sentence break in PHP breaks certain control structures. In PHP, to be exact, the statement or command break ends the execution of the for, foreach, while, do-while or switch control structures in progress, that is, they contain the break between their lines of code (usually between braces).
SWITCH and CASE flowchart
If you understand flowcharts, there’s nothing like seeing one to fully understand the logic of this statement.
This diagram represents the way to interpret and execute a SWITCH with its different cases. As you have seen, when a case PHP of the four shown is true, your code is executed, and terminates. But since the checking of all Cases is done in parallel, only the code of one Case could be executed.
IF code equivalent to SWITCH PHP
The code of the conditional switch above would be equivalent to the following script with IF and ELSE:
<?php if ( $numero == 1 ) { echo '$numero vale 1'; } else if ( $numero == 2 ) { echo '$numero vale 1'; } ?>
The default statement in switch
After seeing how the possible cases of a switch in PHPwe are going to see a special sentence, the defaultstatement that handles the default case.
This statement will be executed when none of the programmed cases are met, that is, when the value of the variable of the switch does not match the values of the case. We could say that it would be the else in a PHP switch.
An example could be:
<?php switch ( $dia_semana ) { case 'sat': echo 'el día es sábado'; break; case 'sun': echo 'el día es domingo'; break; default: echo 'es un día entre semana cualquiera...'; break; } ?>
In this example I treat the possible days of the week, differentiating between the days of the weekend (Saturday and Sunday) and, as you could do with a else When i use if, I try the rest of the options with him. default.
The switch without break in php
Is there a problem if we forget the sentence break? Would the code stop working? No, it wouldn’t stop working, it’s not an error equivalent to forgetting a brace or a semicolon, omitting a break would change the common operation of the switch, so in case of being an error it could be difficult to detect when you start.
really the sentence break usually accompanies almost always the use of case, but it is really written optionally. The omission of a break in one case would cause this, by matching the value of the variable of the switch, would run as normal, but from there, as the break hasn’t stopped code execution, Apache or the php interpreter would continue to execute the following lines, as might be the case with others case either default, and would only stop the execution of switch cases if a break.
Let’s see an example that describes this particular case:
<?php switch ( $dia_semana ) { case 'sat': echo 'el día es sábado'; break; case 'sun': echo 'el día es domingo'; break; case 'mon': case 'tue': case 'wed': case 'thu': case 'fri': echo 'es un día entre semana cualquiera...'; break; } ?>
In this example based on the one in the previous section, I have replaced the default case by cases for each weekday. What will happen? Well, the end result is exactly the same. If the day of the week ($dia_semana) coincides with any of the cases from Monday to Friday (Mon to Fri), since I have not indicated an end of switch by using break, the lines that follow will be executed. Therefore, the message ‘it’s any weekday…’ will be written for any of them (weekdays) and the switch execution will end.
The omission of a break in a case would cause this, by matching the value of the switch variable to execute as normal, but from there, as the break has not stopped code execution, Apache or the php interpreter would continue to execute the following lines.
Advanced switch or with conditions
There is the possibility of programming a switch to behave very similarly to how a chain of IF ELSEIF and ELSE would be done using single or multiple conditions.
This switch transformation is often used when many conditions contain a single code or when the value of the cases can be in one or more ranges.
To achieve this behavior we must somehow end the comparison of the switch variable in PHP, in order to move on to checking the case and its conditions.
Let’s see an example of switch php with conditions for a range of values, exactly the possible ages for working life:
<?php switch ( true ) { case ( $edad < 16 ): echo 'No tienes edad de trabajar, sigue formandote'; break; case ( $edad >= 16 && $edad < 65 ): echo 'Venga, ¿Qué haces aquí? El trabajo te espera; break; case ( $edad >= 65 ): echo 'Disfruta de la tranquilidad, ¡al menos mientras tus nietos te lo permitan!'; break; } ?>
There are two points to note in this example:
- A fixed value (true), which replaces the typical switch variable and allows its execution to be normal.
- Conditions that evaluate to true or false and that are tested one by one, case by case, by using parentheses.
Knowledge to better understand a PHP Switch
- Using variables in php
- Control structures in php
- How to use the if conditional and elseif conditional in php