In the php web development process, the running speed of the website is closely linked to the simplicity and complexity of the code. For example, when we need to refer to When multiple conditions are set to execute different code blocks, PHP-related conditional statements must be used. So how to use concise code to achieve multi-condition judgment? What about statements? This article will give you a detailed introduction to the specific usage and advantages of the PHP switch statement.
Before starting to introduce the switch statement, I recommend that novices read this article of mine [if-related conditionals in PHP How to understand and use the sentence ] will help you understand the knowledge points of this article.
The following will give you a detailed introduction through specific code examples
PHP switch case conditional statement code examples are as follows:
<?php $like="唱歌"; switch ($like) { case "唱歌": echo "你的爱好是唱歌!";//case1 break; case "游泳": echo "你的爱好是游泳!";//case2 break; case "绘画": echo "你的爱好是绘画!";//case3 break; default: echo "你的爱好不是唱歌、不是游泳也不是绘画!"; } ?>
The above code Accessed through a browser, the judgment result is as follows:
The above example is the basic usage of the PHP switch statement. First calculate the value of the $like variable (it can also be an expression), and then
Compare its value with the case value. If it is equal to the case value, the result will be output directly. The break in php switch is used to directly
Prevents the next case code from running. If the above $like is equal to singing, then the value of case1 is output directly. (You can refer to the online tutorial
: [PHP Quick Start Free Tutorial]
Chapter 1 Content-PHP switch statement)
What if we change the value of $like to "reading"? The access effect is shown in the figure below:
Everyone should also pay attention to the default statement in PHP switch. When the value of $like does not belong to case1, 2, or 3 any value in , the default statement will be executed.
In web development, if you encounter multiple conditional judgments, it is much simpler and faster to use the switch statement than the if...elseif statement.
, because switch only requires the value once, while the if...elseif conditional statement needs to be evaluated multiple times before being judged.
This article has certain reference value and I hope it will be helpful to friends in need.
The above is the detailed content of How to write switch case statement? Are there any advantages in php?. For more information, please follow other related articles on the PHP Chinese website!