Switch Function in PHP
Digg! This Page
If you are new to PHP then you should have heard of the IF tag? If so, then Switch works in roughly the same way. Below is a tutorial on how to use it.Step 1
Presuming you have something creating a number or value, like a rand() function. Make it a varible.
$number = rand(1,3);Step 2
The above varible $number will now have a value of randomly picking 1, 2 or 3. Now we shall create the switch tag. The value between the brackets (parentheses) will be the varible of the random number.
switch($number) {
}
Step 3Now normally if you use the IF tag you'll use something like this
if($number == "1") {
echo "1";
} elseif($number == "2") {
echo "2";
} elseif($number == "3") {
echo "3";
} else {
echo "Error";
}But with the switch tag it is presented like this (add this code between the curly brackets of the switch tag)case 1: echo "1"; break; case 2: echo "2"; break; case 3: echo "3"; break; default: echo "Error"; break;You're probably thinking what "eh?", well don't worry it is pretty simple to learn, the value of each "case" is the value of $number, "break;" must be added after each lot of code within the case to clarify its ending. Also you're probably thinking what is the "default" tag for, well that just basically means that if the value is not in one of the "case" statements then load that.
There are various problems that you may come across when using the switch tag in PHP, one of the main ones is if you have a "case" value of, lets say "Dale Hay". Normally it will not work because there is a space in it, so to overcome that, you can just add quotation marks before and after it.
case "Dale Hay": echo "Hello Everyone"; break;Why Use It?
Using it is so much tidier and neater than having tons of IF statements.
Tutorial Example
<?php
$number = rand(1,3);
switch($number) {
case 1:
echo "1";
break;
case 2:
echo "2";
break;
case 3:
echo "3";
break;
default:
echo "Error";
break;
}
?&gr;


