php:switch的用法執行個體分享

來源:互聯網
上載者:User
switch 語句類似於具有同一個運算式的一系列 if 語句。很多場合下需要把同一個變數(或運算式)與很多不同的值比較,並根據它等於哪個值來執行不同的代碼。這正是 switch 語句的用途。

Note: 注意和其它語言不同,continue 語句作用到 switch 上的作用類似於 break。如果在迴圈中有一個 switch 並希望 continue 到外層迴圈中的下一輪迴圈,用 continue 2。

Note:

注意 switch/case 作的是鬆散比較。

執行個體:

<?php  //switch細節  //情況一:數值匹配的時候自動轉換成字串  $a=1;  switch($a){    case "1":echo 'hello1';break;default:echo 'sorry none is the same!';break;  }  echo '<br/>'.'成功退出····';  echo '<hr/>';   //情況二:數值匹配的時候自動轉換成字元  $a=1;  switch($a){    case '1':echo 'hello2';break;default:echo 'sorry none is the same!';break;  }  echo '<br/>'.'成功退出····';  echo '<hr/>';   //情況三:字元匹配的時候自動轉換成數值  $a='1';  switch($a){    case 1:echo 'hello3';break;default:echo 'sorry none is the same!';break;  }  echo '<br/>'.'成功退出····';  echo '<hr/>';   //情況四:字串匹配的時候自動轉換成數值  $a="1";  switch($a){    case 1:echo 'hello4';break;default:echo 'sorry none is the same!';break;  }  echo '<br/>'.'成功退出····';  echo '<hr/>';   //情況五:float也可以匹配  $a=1.1;  switch($a){    case 1.1:echo 'hello5';break;default:echo 'sorry none is the same!';break;  }  echo '<br/>'.'成功退出····';  echo '<hr/>';   //情況六:非0是true  $a=true;  switch($a){    case 1:echo 'hello6';break;case true:echo 'hello61';break;default:echo 'sorry none is the same!';break;  }  echo '<br/>'.'成功退出····';  echo '<hr/>';   //情況七:能匹配boolean  $a=true;  switch($a){    case true:echo 'hello7';break;case 2:echo 'hello71';break;default:echo 'sorry none is the same!';break;  }  echo '<br/>'.'成功退出····';  echo '<hr/>';   //情況八:能匹配null  $a=null;  switch($a){    case 2://''  ""  false 0 都能進入echo 'hello8';break;case null:echo 'hello81';break;default:echo 'sorry none is the same!';break;  }  echo '<br/>'.'成功退出····';  echo '<hr/>';   //情況九:退出順序  $a=5;  switch($a){    case 1:echo 'hello6';break;case 2:echo '我是2號出口';break;case 5:echo '我是5號出口';//break;case true:echo 'hello61';break;default:echo 'sorry none is the same!';break;  }  echo '<br/>'.'成功退出····';  echo '<hr/>';   //情況十:退出順序  $a=50;  switch($a){default:echo 'sorry none is the same!';//break;    case 50:echo 'hello6';//break;case 2:echo '我是2號出口';break;case 5:echo '我是5號出口';//break;case 6:echo 'hello61';break;  }  echo '<br/>'.'成功退出····';  echo '<hr/>';?>

hello1
成功退出····

hello2
成功退出····

hello3
成功退出····

hello4
成功退出····

hello5
成功退出····

hello6
成功退出····

hello7
成功退出····

hello81
成功退出····

我是5號出口hello61
成功退出····

hello6我是2號出口
成功退出····

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.