PHP: switch

The switch statement is wondrous and magic. It's a piece of the language that allows you to select between different options for a value, and run different pieces of code depending on which value is set.

Each possible option is given by a case in the switch statement.

A simple switch statement

switch($bar) { case 4: echo "This is not the number you're looking for.\n"; $foo = 92; }

Delimiting code blocks

The major caveat of switch is that each case will run on into the next one, unless you stop it with break. If the simple case above is extended to cover case 5:


case 4: echo "This is not the number you're looking for.\n"; $foo = 92; case 5: echo "A copy of Ringworld is on its way to you!\n"; $foo = 34;

In the above example of fallthrough, the code for case 4 hasn't been terminated, so it's run on into the code for case 5. $foo ends up as 34, and both messages get printed. The easiest way to stop this is by delimiting the blocks of code with break:

Delimited cases

case 4: echo "This is not the number you're looking for.\n"; $foo = 92; break; case 5: echo "A copy of Ringworld is on its way to you!\n"; $foo = 34; break;

Using fallthrough for multiple cases

Because switch will keep running code until it finds a break, it's easy enough to take the concept of fallthrough and run the same code for more than one case:

Multiple-case code blocks

case 2: case 3: case 4: echo "This is not the number you're looking for.\n"; $foo = 92; break; case 5: echo "A copy of Ringworld is on its way to you!\n"; $foo = 34; break;

In the above code, the code blocks for cases 2 and 3 are empty, and don't have a break; this means that they'll immediately follow on to the code for case 4. In other words, all three cases will run the same code.

The default case

Most of the time, you'll want to run specific code for particular cases, and some kind of "normal situation" code for any other cases. Let's say that the code above deals with a value from 1 to 10; instead of filling in the six missing cases, we can simply give a default:

A default case

default: $foo = 0; break;

Advanced switching: Condition cases

PHP's switch doesn't just allow you to switch on the value of a particular variable: you can use any expression as one of the cases, as long as it gives a value for the case to use. As an example, here's a simple validator written using switch:

Validation with switching

switch(true) { case (strlen($foo) > 30): $error = "The value provided is too long."; $valid = false; break; case (!preg_match('/^[A-Z0-9]+$/i', $foo)): $error = "The value must be alphanumeric."; $valid = false; break; default: $valid = true; break; }

In conclusion

switch is a powerful tool. Use it.

Have your say

If you want to tell me about something I missed, or that I'm wasting my time, please submit a comment below.

Make a comment


raj on Wed 2nd Apr 2014
Emmanuel on Tue 25th Mar 2014
i am a beginner! just wanted to ask why There is no " " on $valid = false; and what does true stands/does on switch(true)cos i just studied switch I GOT THE BASIC switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; default: code to be executed if n is different from both label1 and label2; } but not that much to validation! help please!!!!!
Database Query695 on Wed 12th Mar 2014
You forgot the . loader in case statements like: case (isset($_GET['value']) && $value=$_GET['value'] . is_int($value)):
What does the Fox Say on Sun 23rd Feb 2014
Ken on Wed 27th Nov 2013
In Reply to: R on Sun 4th Aug 2013 Remove the semicolon : from switch($a_count): You either use a semicolon and no {} or a semicolon and endswitch command.
Light on Thu 21st Nov 2013
This web page is a rare gem...
Someone on Fri 15th Nov 2013
How to do: switch(value) { case 1 AND case 2 AND case 3: // Do something break; } So i want it to be if theyre all true do something
R on Sun 4th Aug 2013
What am I doing wrong here? <?php $array = array(0=>"RED",1=>"GREEN"); $a_count = 0; $count = 0; //$p = array(0=>"k", 1=>"s"); //array to simulate person's choice while($count<10) { echo $array[$a_count] . ' '; //PSUEDO FOR IMAGE BEING DISPLAYED switch($a_count): { case 1: echo "This is RED.<br>"; $a_count = 0; break; case 0: echo "This is GREEN.<br>"; $a_count++; break; } $count++; } ?>
a on Tue 28th May 2013
come on
blah on Thu 23rd May 2013
if elseif elseif elseif else Who needs switch?
TMKCodes on Fri 9th Mar 2012
It is also possible to use switch with this syntax. switch($var) : case 1: break; default: endswitch;
palcov on Tue 4th Oct 2011
it is possible to use same case more imes than one in switch? thanks.
ss on Tue 27th Sep 2011
switch(true){ case ( ($send_data['rcv_resource']=='wood'|| $send_data['rcv_resource']=='Wood' || $send_data['another_worker_data'][0]['resource_type']=='W') && ($send_data['rcv_resource']=='food'|| $send_data['rcv_resource']=='Food' || $send_data['another_worker_data'][0]['resource_type']=='F')): if($send_data['another_worker_data'][0]['resource_type']=='W'){ $cur_wood=$send_data['city_data'][0]['wood']+($another_food_finished_before*($send_data['another_worker_data'][0]['inc_rate']/(60*PERIOD)))+($outer_wood_income*.30); } else{ $cur_wood=$send_data['city_data'][0]['wood']+($food_finished_before*($send_data['worker_data'][0]['inc_rate']/(60*PERIOD)))+($outer_wood_income*.30); } if($send_data['another_worker_data'][0]['resource_type']=='F'){ $cur_food=$send_data['city_data'][0]['food']+($another_food_finished_before*($send_data['another_worker_data'][0]['inc_rate']/(60*PERIOD)))-$send_data['new_update']+($outer_food_income*.30); } else{ $cur_food=$send_data['city_data'][0]['food']+($food_finished_before*($send_data['worker_data'][0]['inc_rate']/(60*PERIOD)))-$send_data['new_update']+($outer_food_income*.30); } $cur_stone=$send_data['city_data'][0]['stone']+($outer_stone_income*.30); $cur_iron=$send_data['city_data'][0]['iron']+($outer_iron_income*.30); break; case (( $send_data['rcv_resource']=='food'|| $send_data['rcv_resource']=='Food' || $send_data['another_worker_data'][0]['resource_type']=='F') && ($send_data['rcv_resource']=='stone'|| $send_data['rcv_resource']=='Stone' || $send_data['another_worker_data'][0]['resource_type']=='S') ): $cur_wood=$send_data['city_data'][0]['wood']+($outer_wood_income*.30); if($send_data['another_worker_data'][0]['resource_type']=='F'){ $cur_food=$send_data['city_data'][0]['food']+($another_food_finished_before*($send_data['another_worker_data'][0]['inc_rate']/(60*PERIOD)))+($outer_food_income*.30); } else{ $cur_food=$send_data['city_data'][0]['food']+($food_finished_before*($send_data['worker_data'][0]['inc_rate']/(60*PERIOD)))+($outer_food_income*.30); } if($send_data['another_worker_data'][0]['resource_type']=='S'){ $cur_stone=$send_data['city_data'][0]['stone']+($another_food_finished_before*($send_data['another_worker_data'][0]['inc_rate']/(60*PERIOD)))+($outer_stone_income*.30); } else{ $cur_stone=$send_data['city_data'][0]['stone']+($food_finished_before*($send_data['worker_data'][0]['inc_rate']/(60*PERIOD)))+($outer_stone_income*.30); } $cur_iron=$send_data['city_data'][0]['iron']+($outer_iron_income*.30); break; }
lasavior on Tue 23rd Aug 2011
Thank you for the valuable information about using it with conditional arguments. This information is not documented on and is incredibly handy to know.
Ayesh on Tue 5th Jul 2011
This is awesome as switch! You have registered a domain to put this small but valuable thing and thanks for that effort! Keep it up!
Joseph Thayne on Mon 6th Jun 2011
This is an awesome explanation. It is the only place I have found (including that simply and accurately describes fallthrough in this. Thank you for the resource.
tejus on Wed 7th Jan 2009
O wow I expect phpif, phpfor, phpwhile etc. That would be really cool.
Kevin Waterson on Sun 28th Dec 2008
Nice stuff Imran. I now have a resource to point the newbs to
when they visit asking about if/else or switch.
Sean on Fri 5th Dec 2008
Imran, you're a tool! Bye!
kryps on Fri 5th Dec 2008
Condition cases, woot
wow. on Thu 4th Dec 2008
just.... wow.
microsoft whore on Tue 2nd Dec 2008
what is php?
André Ferreira on Tue 2nd Dec 2008
This is the best website in all of the interwebs!
erf on Mon 1st Dec 2008
notQube on Mon 1st Dec 2008
wonderously magical
Mikko on Mon 1st Dec 2008
I feel that this site is a valuable contribution to the PHP community.
Ox40 on Mon 1st Dec 2008
is teh best lulz
phpswitch lover on Mon 1st Dec 2008
try: switch($var) { case "" case "": echo "is a waste of time"; }