PHP How to use the switch() method

Demo
Download

Many conditional statements can be written with either the switch function or if else syntax, and today we’re going to concentrate on switch() and the proper time to use it. When it comes to changing through page names (ex: index.php?p=games), switch() is better to use rather than an if else clause. For one, it tends to cut down on code length and clarity, and second, switch() offers a default case, which is put to perfect use if the ‘p’ variable (?p=) is left empty by the browsing user. Here is an example of switching between page names:

  <?php 
 if(isset($_GET['p'])) {
 	$page = $_GET['p'];
 
 	switch($page) {
 		case 'home':
 			include('home.php');
 			break;
 		
 		case 'about':
 			include('about.php');
 			break;
 			
 		case 'downloads':
 			include('downloads.php');
 			break;
 		
 		default:
 			include('home.php');
 			break;
 	} 
 } else {
 	$page = 'home';
 }
?>

At the beginning of the script we check to see if p is set or not, meaning has the page changed. If it is not set, the user has probably just logged onto the page, and the default page value is set to home. When the user does change to a new page by clicking the link, $_GET[‘p’] grabs the page value from the URL and sets it to the $page variable.

When $page holds a value, the switch statement comes into play and includes whatever file is associated with that switch case. If the $page variable is set to a value in which there is no associated case, then the default case is used. In this tutorial, the default case is ‘home’ and will include the home.php file.

Each case will execute the code associated block until it hits a break statement, which ends the cycle.

This article has 2 comments

  1. Pingback: PHP: Looping through an array using foreach with if else and switch functionality

  2. Pingback: PHP & MySQL: How to Store IP Addresses using PHP & MySQL

Leave a Comment

Your email address will not be published. Required fields are marked *