Switch Statement

  • Description : The switch statement can be used to evaluate a variable and execute code depending on the result.
  • Language : PHP
  • Date Added : 13th October, 2009
Bookmark and Share

A switch statement is most commonly used you have too many possible outcomes/conditions for an if statement. Below is the basic structure of a switch statement:

Code :
<?php switch (variable) { case value1: code to be executed if variable=value1; break; case value2: code to be executed if variable=value2; break; case value3: code to be executed if variable=value3; break; default: code to be executed if variable does not equal the above cases } ?>

This might appear confusing, but if you look at the working example below it will(hopefully) made more sense!

Code :
<?php $variable = "bob"; switch ($variable) { case "harry": echo "Hello harry!"; break; case "bob": echo "Hello bob!"; break; case "sarah": echo "Hello sarah!"; break; default: echo "Hello, I don't know your name!"; } ?>
Output:
Hello bob!

And if we changed the variable...

Code :
<?php $variable = "Ashley"; switch ($variable) { case "harry": echo "Hello harry!"; break; case "bob": echo "Hello bob!"; break; case "sarah": echo "Hello sarah!"; break; default: echo "Hello, I don't know your name!"; } ?>
Output:
Hello, I don't know your name!

Switch statements are quite simple, but extremely useful for evaluating a variable(often user input) and then taking a certain path through your script. In the next tutorial we will look at the $_GET function



Login Required

To post comments you must sign in to your account below!

User :
Pass :

If you do not currently have an account click here to create one now!