dalehay.com
Search Engine Optimization

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 3
Now 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.

Problems
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;

Comments

Comments:

Add your comment...

Your Name:

Your Email:

Your Comment:

Enter This Number:

(60615)


Note: Your IP address is saved into the database when you submit a comment. Any type of threatening behaviour will result in your ISP being contacted and legal action being taken place!





Latest News Stories
» BBC Breakfast Error...
» Fact about December 26th
» Creating a new online website idea
» Analog TV Website Pages
» Will It Blend?
» MTV to remake Rocky Horror Picture Show
Top Viewed Stories
» PHP Mini Message Board Tutorial (1166)
» PHP Search Engine Tutorial (431)
» Helen Willetts Pregnant? (213)
» Will It Blend? (185)
» Create your own Image Uploader (176)
» MTV to remake Rocky Horror Picture Show (160)
Most Commented Stories
» I like my DuMP (15)
» Create your own Image Uploader (15)
» PHP Mini Message Board Tutorial (9)
» I'm on Wikipedia! (7)
» Chocie Munchin Niece (6)
» Life on Mars... (6)