PHP Switch Statement

A PHP switch statement is a conditional statement used to execute different code based on what the conditional expression evaluates to. The keyword "case" followed by the value is used to match the values from the conditional expression.

$animals = array('Cat', 'Dog', 'Duck', 'Cow', 'Cricket', 'Hyena', 'Chinchilla'); //conditional expression switch ( $animals[array_rand( $animals )] ) { case 'Cat': echo "Meow!"; break; case 'Dog': echo "Woof!"; break; case 'Duck': echo 'Quack!'; break; case 'Cricket': echo 'Chirp!'; break; case 'Hyena': echo 'He-he-he-he!'; break; case 'Chinchilla': echo 'Squeak!'; break; case 'Cow': echo 'Moooooo!'; break; }

I used array_rand() function above which picks out a random key index within the array. I then put the resulting value returned from array_rand() inside of $animals[ ] array's square brackets, so the final result is a random value from the $animals array. Note that I didn't create another variable holding the random value returned from array_rand() function, but rather put the entire function inside of square brackets right away. This is perfectly okay today in PHP and results in a cleaner, shorter code.

Default

Switch statement can also have default keyword which will execute the code if no cases have been matched:

switch ( $animals[array_rand( $animals )] ) { case 'Cat': echo "Meow!"; break; case 'Dog': echo "Woof!"; break; default: echo "Unknown animal detected! Run for your life!"; }

Switch Without Breaks

You can also omit using break; after the case statement. Doing so will continuing passing the case match to the next one, until it reaches the end of a switch statement:

$speed = '65mph'; switch ( $speed ) { case '65mph': echo "You're going the speed limit, responsible driver!"; case '95mph': echo "Whoa there, slow down, you're way over the speed limit!"; case '135mph': echo "Did you forget about your breaks?"; case '250mph': echo "You must be driving Bugatti"; } /* output: You're going the speed limit, responsible driver! Whoa there, slow down, you're way over the speed limit! Did you forget about your breaks? You must be driving Bugatti */

Case Grouping

It's possible to group multiple case matches by having an empty case condition, which will pass the control over to the next case:

$species = array('Cat','Dog','Cow','Fly','Bee','Ant'); switch ( $species[array_rand( $species )] ) { case 'Cat': case 'Dog': case 'Cow': echo 'We are animals!'; break; case 'Fly': case 'Bee': case 'Ant': echo 'We are insects!'; break; }

Alternative Switch Case Syntax

PHP also supports an alternative syntax for switch statement, so instead of using the curly brackets we can replace it with a colon (:) and endswitch; which will look like this:

switch ( $i ): case 0: echo "i equals 0"; break; case 1: echo "i equals 1"; break; case 2: echo "i equals 2"; break; default: echo "i is not equal to 0, 1 or 2"; endswitch;

Switch vs Else If

One important difference to note between switch case and else if is that in the switch case the conditional expression is only evaluated once. On the other hand, in an else if statement the condition keeps being evaluated.

$number = 5; switch ( $number ) //condition is only evaluated once { case 5: echo "Number 5 matched!"; break; case 3: echo "Number is less than 5!"; break; case 4: echo "Number is less than 5!"; break; } //output: Number 5 matched! if ( $number > 5 ) //condition evaluated first time { echo "Number is greater than 5!"; } elseif ( $number < 10 ) //condition evaluated second time { echo "Number is less than 10!"; } //output: Number is less than 10!

Practical Switch

The following function uses switch statement and will return the name of the animal based on the year provided.

//code credit: Anonymous function getChineseZodiac($year) { switch ($year % 12) : case 0: return 'Monkey'; // Years 0, 12, 1200, 2004... case 1: return 'Rooster'; case 2: return 'Dog'; case 3: return 'Boar'; case 4: return 'Rat'; case 5: return 'Ox'; case 6: return 'Tiger'; case 7: return 'Rabit'; case 8: return 'Dragon'; case 9: return 'Snake'; case 10: return 'Horse'; case 11: return 'Lamb'; endswitch; } echo getChineseZodiac(2017); //output: Rooster

And another cool one for easy Nobel prize winning:

//code credit: MaxTheDragon at home dot nl function winNobelPrizeStartingFromBirth( $subject ) { switch( $subject ) { case "peace": echo "You won the Nobel Peace Prize!"; break; case "physics": echo "You won the Nobel Prize in Physics!"; break; case "chemistry": echo "You won the Nobel Prize in Chemistry!"; break; case "medicine": echo "You won the Nobel Prize in Medicine!"; break; case "literature": echo "You won the Nobel Prize in Literature!"; break; default: echo "You bought a rusty iron medal from a shady guy who insists it's a Nobel Prize..."; break; } } winNobelPrizeStartingFromBirth("chemistry"); //output: "You won the Nobel Prize in Chemistry!"