The Switch statement in PHP is used to perform one of several different actions based on one of several different conditions.
PHP SwitchÓï¾äµÄ×÷ÓÃÊÇ£º¸ù¾Ý²»Í¬µÄÌõ¼þ£¬Ö´Ðв»Í¬µÄÓï¾ä¡£
The Switch Statement
SwitchÓï¾ä
If you want to select one of many blocks of code to be executed, use the Switch statement.
Èç¹ûÄãÏëͬʱÅж϶àÖÖÌõ¼þ£¬²¢Ö´ÐÐÆäÖÐÒ»ÖÖ·ûºÏÌõ¼þµÄ´úÂ룬ÄÇô¿ÉÒÔʹÓÓswitch”Óï¾ä¡£
The switch statement is used to avoid long blocks of if..elseif..else code.
ʹÓÃswitchÓï¾ä¿ÉÒÔ±ÜÃâͬʱʹÓöà¸ö“if...elseif...else”´úÂ룬ÏÖÔÚ½ÏΪ¼ò±ã¡£
Syntax
Óï·¨
switch (±í´ïʽ) { case label1: µ± ±í´ïʽ = label1 ʱ¾ÍÖ´ÐÐÕâ¶Î´úÂë; break; case label2:
µ± ±í´ïʽ = label2 ʱ¾ÍÖ´ÐÐÕâ¶Î´úÂë; break; default: µ±±í´ïʽΪÆäËüÇé¿öµÄʱºò¾ÍÖ´ÐÐÕâ¶Î´úÂë; }
|
Example
°¸Àý
This is how it works:
ÏÂÃæ½éÉÜËüµÄ¹¤×÷ÔÀí£º
- A single expression (most often a variable) is evaluated once
Öð¸öµØÖ´ÐÐÌõ¼þÖÐÔ¤ÏÈÉ趨µÄ±í´ïʽ»ò¼ÆËã±äÁ¿£»
- The value of the expression is compared with the values for each case in the structure
½«Ìõ¼þÖÐÔ¤ÏÈÉ趨µÄ±í´ïʽ»ò±äÁ¿µÄÖµÓë´úÂëÖÐÉ趨µÄÌõ¼þÏà±È½Ï£»
- If there is a match, the code associated with that case is executed
Èç¹ûÉÏÊö¶þÕ߯¥Å䣬ÄÇôÓëÕâ¸öÌõ¼þÏà¹ØµÄ´úÂ뽫±»Ö´ÐУ»
- After a code is executed, break is used to stop the code from running into the next case
ÔÚÒ»¶Î·ûºÏÌõ¼þµÄ´úÂë±»Ö´ÐÐÒԺ󣬿ÉÒÔʹÓÓbreak”Ìø³öSwitchÓï¾ä£»
- The default statement is used if none of the cases are true
µ±ËùÓеÄÌõ¼þ¶¼ÊǼÙ[false]ʱ£¬ÔòÖ´ÐÐdefaultÓï¾ä£»
<html> <body>
<?php switch ($x) { case 1: echo "Êý×Ö 1"; break; case 2: echo "Êý×Ö 2"; break; case 3: echo "Êý×Ö 3"; break; default: echo "Õâ¸öÊý²»µÈÓÚ1¡¢2ºÍ3"; } ?>
</body> </html>
|