In the process of PHP web development, the speed of the website is closely related to the simplicity and complexity of the code. For example, when we need to specify a variety of conditions to execute different blocks of code, it is necessary to use the PHP related conditional statements, then how to use concise code to implement the multi-conditional judgment statement? This article will give you a detailed introduction to the specific use of PHP switch statements and advantages.
Before you begin to introduce the switch statement, it is recommended that novice white readers read my article, "How to use the IF-related conditional statement in PHP," to have an assistant Jiuben article Knowledge point.
So here's a detailed code example to give you a full introduction
The PHP switch case Condition Statement code example is as follows:
<?php$like= "singing"; switch ($like) {case "singing": echo "Your hobby is singing!"; /case1 break ; Case "Swim": echo "Your hobby is swimming!"; /case2 break ; Case "painting": echo "Your hobby is painting!"; /case3 break ; Default: echo "Your hobby is not singing, swimming or painting!" ";}? >
The above code is accessed through the browser, judging the results such as:
The above example is the basic use of the PHP switch statement. First, the value of the $like variable is computed (or it can be an expression), and then the value is compared to the case value, and if the result is directly output if it is equal to the value of the instance, break in PHP switch is used to directly block the next case code from running. If the above $like equals singing, then output the CASE1 value directly. (You can refer to the online tutorial: "PHP QuickStart Free Tutorial" in the first chapter of the content-php switch statement)
What if we change the value of $like to "read"? Its access effect is as follows:
It is also important to note that the default statement in PHP switch executes the default statement when the value of $like does not belong to any of the values in Case1, 2, and 3.
In web development, it is much simpler and quicker to use a switch statement than a If...elseif statement if it encounters multiple criteria, because switch requires only one value at a time, and the If...elseif conditional statement needs to be evaluated multiple times.