這一講海源川匯網絡給大家講解PHP的網站建設課程中的PHP Switch語句,PHP 中的 Switch語句用于執(zhí)行基于多個不同條件的不同動作。
如果您希望有選擇地執(zhí)行若干代碼塊之一,請使用 Switch 語句,從而可以避免冗長的 if..elseif..else 代碼塊。
語法
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;
}
switch語句工作原理:
1、對表達式(通常是變量)進行一次計算
2、把表達式的值與結構中 case 的值進行比較
3、如果存在匹配,則執(zhí)行與 case 關聯(lián)的代碼
4、代碼執(zhí)行后,break 語句阻止代碼跳入下一個 case 中繼續(xù)執(zhí)行
5、如果沒有 case 為真,則使用 default 語句
<html>
<head>
<?php
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?>
</body>
</html>
以上是海源川匯對PHP switch語句的講解,在網站制作過程中switch語句操作是我們要經常使用的,希望大家好好領會。