PHP คำสั่ง Switch
- Page Previous PHP If...Else
- Page Next PHP While Loop
คำสั่ง switch ใช้เพื่อทำงานตามเงื่อนไขต่างๆ
คำสั่ง Switch สเตรส
หากคุณต้องการที่จะทำงานเลือกตัวหนึ่งในบรรดาบล็อครหัสหลายบล็อค โปรดใช้คำสั่ง Switch
ใช้คำสั่ง Switch สามารถป้องกันการเขียนรหัสเกินกว่าจำนวนที่จำเป็นของ if..elseif..else ได้
Syntax
switch (expression) { case label1: Code to be executed when expression = label1 ; break; case label2: Code to be executed when expression = label2 ; break; default: Code to be executed when the value of the expression is not equal to label1 and label2 }
Working principle:
- Perform a single calculation of the expression (usually a variable)
- Compare the value of the expression with the value of the case in the structure
- If there is a match, execute the code associated with the case
- After the code is executed,Break statementPrevent the code from jumping into the next case and continuing to execute
- If no case is true, use the default statement
Example
<?php $favfruit="orange"; switch ($favfruit) { case "apple": echo "Your favorite fruit is apple!"; break; case "banana": echo "Your favorite fruit is banana!"; break; case "orange": echo "Your favorite fruit is orange!"; break; default: echo "Your favorite fruit is neither apple, banana, or orange!"; } ?>
- Page Previous PHP If...Else
- Page Next PHP While Loop