Jump to content

What is the use of switch statement in php


zeeshan

Recommended Posts

PHP is not just about logins you know. It can do far more.The switch statement compares the value of a single variable against other values. You can use it to define different actions for different values of a variable. For example, if you have the fileindex.php

<?phpswitch($_GET['number']) {	case '1':		//What to do if $_GET['number'] === '1'		$entered = 'one';		break;	case '4':		//What to do if $_GET['number'] === '4'		$entered = 'four';		break;	case '6':		//What to do if $_GET['number'] === '6'		$entered = 'six';		break;	default:		//What to do if $_GET['number'] is anything else, or is not present		$entered = 'not recognized';		break;}echo "The number you entered is $entered";?>

and access it like

index.php?number=1

you'll see

The number you entered is one
and if you access it like
index.php?number=4

you'll instead see

The number you entered is four
and if accessed like
index.php?number=6

the script would say

The number you entered is six
In all other cases, you'll see
The number you entered is not recognized
The switch statement is a good replacement (and I think more efficient in some cases) for a series of if...elseif statements comparing the same variable. For example, the above script could be rewritten to
<?phpif ($_GET['number'] === '1') {	//What to do if $_GET['number'] === '1'	$entered = 'one';}elseif ($_GET['number'] === '4') {	//What to do if $_GET['number'] === '4'	$entered = 'four';}elseif ($_GET['number'] === '6') {	//What to do if $_GET['number'] === '6'	$entered = 'six';}else {	//What to do if $_GET['number'] is anything else, or is not present	$entered = 'not recognized';}echo "The number you entered is $entered";?>

but the switch() is just nicer.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...