English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn how to use switch-The case statement is used to test or evaluate expressions with different values in PHP.
switch-The case statement is like if-elseif-An alternative to the else statement, it performs almost the same operation. switch-The case statement tests a variable against a series of values until a match is found, and then executes the code block associated with the match.
switch(n){ case label1: // The code to be executed when n = label1 break; case label2: // The code to be executed when n = label2 break; ... default: // The code to be executed when n does not match any of the labels }
See the following example, which displays different messages every day.
<?php $today = date("D"); switch($today){ case "Mon": echo "Today is Monday. Clean your house."; break; case "Tue": echo "Today is Tuesday. Buy some food."; break; case "Wed": echo "Today is Wednesday. Go see a doctor."; break; case "Thu": echo "Today is Thursday. Fix your car."; break; case "Fri": echo "Today is Friday. Let's have a party tonight."; break; case "Sat": echo "Today is Saturday. It's time to watch a movie."; break; case "Sun": echo "Today is Sunday. Take a rest."; break; default: echo "No available information today."; break; } ?>Test and see‹/›
switch-case statement vs if-elseif-The difference between the else statement and the switch statement lies in an important aspect. The switch statement executes line by line (i.e., statement by statement), and once PHP finds a case statement with a condition expression that is true, it not only executes the code associated with the case statement but also executes all subsequent case statements until the statement ends. It automatically switches to the end of the switch block.
To prevent this situation, please add a break statement at the end of each case block. The break statement tells PHP to exit the switch once the code associated with the first real case has been executed.-case block.