دستورات Switch در PHP
- Previous Page PHP If...Else
- Next Page PHP While Loop
دستور switch برای اجرای عملیاتهای مختلف بر اساس شرایط مختلف استفاده میشود.
دستور Switch
اگر میخواهید یکی از چند کد مورد نظر خود را انتخاب و اجرا کنید، از دستور Switch استفاده کنید.
استفاده از دستور Switch میتواند از کد طولانی if..elseif..else جلوگیری کند.
Syntax
switch (expression) { case label1: The code to be executed when expression = label1 ; break; case label2: The code to be executed when expression = label2 ; break; default: The 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 execution,break statementPrevent the code from jumping into the next case to continue executing
- 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!"; } ?>
- Previous Page PHP If...Else
- Next Page PHP While Loop