search
HomeBackend DevelopmentPHP TutorialDetailed explanation of the use of switch in PHP
Detailed explanation of the use of switch in PHPJan 05, 2018 am 11:19 AM
phpswitchExample

switch statement is used to perform different actions based on different conditions. This article introduces you to a detailed usage example of the switch statement in PHP. It involves knowledge points about switch usage. Friends who are interested in switch usage can learn together through this article. I hope to be helpful.

switch is a switch statement, so many friends only know how to use a simple switch statement. Below, the editor of Yiju Tutorial will introduce you to a detailed usage example of switch.

The reason why it is called "advanced" usage is because I haven't even mastered the most basic usage of switch, so what I will talk about next is actually its basic usage!

The switch statement is similar to a series of IF statements with the same expression. There are many situations where you need to compare the same variable (or expression) with many different values ​​and execute different code depending on which value it equals. This is exactly what the switch statement is for.
Note: Note that unlike other languages, the continue statement acts similarly to break when applied to switch. If you have a switch in a loop and want to continue to the next iteration in the outer loop, use continue 2.

The following two examples use two different methods to achieve the same thing, one using a series of if statements, the other using a switch statement:

Example #1 switch Structure

<?php
if ($i == 0)
{
 echo "i equals 0";
}
elseif ($i == 1)
{
 echo "i equals 1";
}
elseif ($i == 2)
{
 echo "i equals 2";
}
switch ($i)
{
 case 0:
 echo "i equals 0";
 break;
 case 1:
 echo "i equals 1";
 break;
 case 2:
 echo "i equals 2";
 break;
}
?>

Example #2 The switch structure can use strings

<?php
switch ($i)
{
 case "apple":
 echo "i is apple";
 break;
 case "bar":
 echo "i is bar";
 break;
 case "cake":
 echo "i is cake";
 break;
}
?>

Key points: (This is what I have never mastered before!)

To avoid errors, it is very important to understand how switch is executed. The switch statements are executed line by line (actually statement by statement). Initially no code is executed. Only when the value in a case statement matches the value of the switch expression will PHP start executing the statement until the end of the switch block (such as a return statement) or until the first break statement is encountered. If you do not write break at the end of the statement segment of the case, PHP will continue to execute the statement segment in the next case. For example:

<?php
switch ($i)
{
 case 0:
 echo "i equals 0";
 case 1:
 echo "i equals 1";
 case 2:
 echo "i equals 2";
}
?>

Special note: If $i is equal to 3, PHP will not execute any echo statement! However, if $i equals 0, PHP will execute all echo statements! If $i equals 1, PHP will execute the next two echo statements. Only if $i equals 2 do you get the "expected" result - just "i equals 2". Therefore, it is important not to forget break statements (even when you deliberately want to avoid providing them in some cases).

[Efficiency] The condition in the switch statement is only evaluated once and used to compare with each case statement. The condition is evaluated again in the elseif statement. If the condition is more complex than a simple comparison or is in a loop many times, it may be faster to use a switch statement.

The statements in a case can also be empty, which only transfers control to the statements in the next case.

<?php
switch ($i)
{
 case 0:
 case 1:
 case 2:
 echo "i is less than 3 but not negative";
 break;
 case 3:
 echo "i is 3";
}
?>

A special case of case is default. It matches any case that does not match any other case. For example, the

<?php
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";
}
?>

case expression can be any expression that evaluates to a simple type, that is, an integer or floating point number as well as a string. Arrays or objects cannot be used unless they are dereferenced to simple types.

[Practical] Based on the above knowledge points, write a function like this: Calculate the number of bytes actually represented by the capacity value

<?php
/**
 * 返回字节数
 *
 * @param string $val 如 400M
 */
function return_bytes($val = &#39;&#39;)
{
 $val = trim($val);
 $last = strtolower($val{strlen($val)-1});
 switch ($last)
 {
 case &#39;g&#39;:
  $val *= 1024;
 case &#39;m&#39;:
  $val *= 1024;
 case &#39;k&#39;:
  $val *= 1024;
 }
 return $val;
}
$memorylimit = ini_get(&#39;memory_limit&#39;);
echo $memorylimit, &#39;<br/>&#39;;
echo return_bytes($memorylimit);
输出:
400M
419430400

Special note: When $val = 400M, case ' m' is hit, and $val *= 1024; below it is executed, but because there is no break language, case 'k' will continue to be hit, and the $val *= 1024; statement below it will be executed, so, overall it is quite Yu executed 400 * 1024 * 1024.

Related recommendations:

Detailed explanation of using PHP to find the longest common substring of two strings

Detailed explanation of how PHP generates vcf vcard files

Detailed explanation of PHP high-precision operation BC function library

The above is the detailed content of Detailed explanation of the use of switch in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
switch日版港版有什么区别switch日版港版有什么区别Jun 20, 2023 pm 02:06 PM

switch日版港版的区别:1、充电器上存在主要区别,日版和国标充电口通用,港版使用英式三角插头;2、日版使用点卡支付,而港服使用支付宝支付;3、港版售后保修需要邮寄回HK售后点,而日版需要邮寄到Japan指定售后点。

switch连电视没反应怎么办switch连电视没反应怎么办Jul 03, 2023 am 11:15 AM

switch连电视没反应解决方法:1、检查switch和电视的电源是否连接;2、检查电视HDMI线接口是否插紧;3、Switch底座后盖打开,检查电源线和HDMI线是否插紧;4、检查Switch是否开机状态下放入底座;5、检查电视是否切换了信号源。

switch可以一直放在底座上充电吗switch可以一直放在底座上充电吗Jul 06, 2023 pm 04:51 PM

switch不可以一直放在底座上充电,其危害有:1、缩短电池的寿命和续航时间;2、导致内存烧坏。

艾尔登法环switch能玩么艾尔登法环switch能玩么Mar 11, 2024 am 11:31 AM

艾尔登法环能在switch上游玩吗?艾尔登法环作为一款极具魅力的动作RPG游戏,不少朋友可能还不明白它能否在switch平台上进行畅快游玩,答案是暂时无法实现。艾尔登法环switch能玩么答:不能在switch游玩。此款备受瞩目的魂系列角色扮演类动作游戏已正式发布,玩家可前往PC、ps4/5以及XboxSerieseX|S/XboxOne购买并立即体验。许多拥有switch的朋友们可能仍热切期待在ns上畅享这款游戏,但遗憾的说,该游戏并无switch版本。据官网配置要求显示,游戏配置较高,而sw

switch lite和switch有什么区别switch lite和switch有什么区别Jun 28, 2023 pm 02:13 PM

switch lite和switch区别有:1、尺寸不同;2、屏幕大小及机身重量不同;3、手柄是否可拆卸及手柄功能不同;4、电池续航能力不同;5、手柄按键设计不同;6、可支持游戏不同;6、颜色不同。

switch语句中必须有default选项吗?switch语句中必须有default选项吗?Nov 25, 2020 pm 04:03 PM

switch语句中不是必须有default选项的。switch语句首先会找满足条件的case值做为执行后面的程序入口,若所有的case都不满足,则找default入口,若未找到则退出整个语句;default只是一个备用入口,有没有都无所谓。

switch32g内存够用吗switch32g内存够用吗Jun 20, 2023 pm 02:28 PM

switch32g内存不够用,其原因如下:1、买数字版游戏想购买DLC截图储存到掌机里的话根本不够用;2、下载数字版游戏,32G内存大约可以储存2~3个游戏,根本满足不了玩游戏的需求;3、数字游戏及其dlc一般保持在5G,除过自带系统占用的空间,下载游戏对于玩家来说比较困难。

消息称世嘉拥有任天堂 Switch 2 开发套件,《FF7:R》在 Switch 2 上运行效果看上去像 PS5 游戏消息称世嘉拥有任天堂 Switch 2 开发套件,《FF7:R》在 Switch 2 上运行效果看上去像 PS5 游戏Sep 10, 2023 pm 05:33 PM

本站9月2日消息,Reddit论坛用户TheRealImAHeroToo爆料称,世嘉拥有Switch2开发套件已经有一段时间了,新主机将具备新的相机功能,可向下兼容一些经过测试的游戏。SquareEnix拥有新款PS5开发套件,而《最终幻想7:重制版》在Switch2上运行的效果看上去像PS5游戏。目前该爆料者的账号已经删除,并表示不会再泄露信息,因为风险太大。本站注意到,该爆料者还提到:明年将推出另一款世嘉的索尼克游戏《女神异闻录6》或许不会在明年发布,主题是“黑与白”;还有一款尚未公布的《女

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool