Categories

Articles in Basics Category

PHP If Else and Switch Case

If Else and Switch Case are control structures that let you execute code segments based on given conditions. These build up the dynamic behavior of PHP.

If

Think that you are writing a PHP program for a store and you have some offers based on the age. Following is a single if condition that would show some special offers if the user is a teenage. It won’t show any offer if the user belongs to any other age group.

if (($age > 12) && ($age < 20)) {
	// Show teenage offers
}

If Else

Think that you have got some general offers to other age groups. Then you can attach an else statement to show those offers if the user is not a teenage.

if (($age > 12) && ($age < 20)) {
	// Show teenage offers
} else {
	// Show general offers
}

If Elseif

If you are going to introduce some adult offers (say for age over 40), you can use an elseif and have another condition to check whether the age is above 40.

if (($age > 12) && ($age < 20)) {
	// Show teenage offers
} elseif ($age > 40) {
	// Show adult offers
} else {
	// Show general offers
}

Above code would first check whether the user is a teenage. If not, it would check whether if he is an adult. If that is also false, it would go to the else block. Like this, you can have more elseif blocks if you have offers for more age groups.

Having else block at the end is optional. You can decide not to show any offer if the user doesn’t belong to any of your defined age groups.

Condition of If Statements

Note that condition of if statements should always result in either true or false. If the result is true, immediate code block would be executed. If it is false, control will go to next elseif condition or else block depending on their availability.

Switch Case

Switch Case acts similar to Elseif control structure. Main difference is that Switch Case can be written in a way that it compares a given value with a set of predefined values without evaluating set of conditions.

$day = 'Wednesday';

switch ($day) {

	case 'Monday':
		echo 'Wish you a fresh start!';
		break;

	case 'Wednesday':
		echo 'Keep going. Good luck!';
		break;

	case 'Friday':
		echo 'Happy weekend!';
		break;

	default:
		echo 'Good day!';
		break;

}

default is the code block that would be executed if the given value is not matched with any of the pre-defined values. It acts similar to Else in If control structures and is optional.

If you don’t specify a break statement in a case block then PHP will execute next blocks till it finds a break statement. You can use this behavior if you need to have same output for more than one case.

switch ($day) {

	case 'Monday':
		echo 'Wish you a fresh start!';
		break;

	case 'Tuesday':

	case 'Wednesday':

	case 'Thursday':
		echo 'Keep going. Good luck!';
		break;

	case 'Friday':
		echo 'Happy weekend!';
		break;

	default:
		echo 'Good day!';
		break;

}

In above code, if $day matches to Tuesday, Wednesday or Thursday, it will print ‘Keep going. Good luck!’.

If Else vs Switch Case

If Else can be used for any occasion where comparisons need to be done. Each If statement checks a condition and operands associated with the condition can be different from one If to another attached Elseif.

Switch Case is good to use when the same value is compared against a set of values. In Switch Case, since usually there are no conditions to evaluate, it can be bit efficient over an Elseif counterpart.

Though it’s not common, conditions can be used in Switch Case. Both Elseif and Switch Case below work the same way. Boolean true is passed to the Switch so that execution will always be passed to the inside code blocks.

$day = 'Friday';
$longShift = true;

if ($day == 'Monday') {
	echo 'Wish you a fresh start!';
} elseif ($day == 'Wednesday') {
	echo 'Keep going. Good luck!';
} elseif ($day == 'Friday' && !$longShift) {
	echo 'Happy weekend!';
} else {
	echo 'Good day!';
}
$day = 'Friday';
$longShift = true;

switch (true) {

	case ($day == 'Monday'):
		echo 'Wish you a fresh start!';
		break;

	case ($day == 'Wednesday'):
		echo 'Keep going. Good luck!';
		break;

	case ($day == 'Friday' && !$longShift):
		echo 'Happy weekend!';
		break;

	default:
		echo 'Good day!';
		break;

}

Ternary Operator (Shorthand If/Else)

Ternary operator let us return one of two values based on a given condition. It’s syntax is like below.

(expression)?(if expression is true):(if expression is false)

In following example, if current time is less than 12 noon, it will print Good Morning! else it will print Welcome!. You can see that ternary operator let us evaluate conditions in one line.

echo (date('G') < 12) ? 'Good Morning!' : 'Welcome!';

We could also assign the value to a variable and print.

$greeting = (date('G') < 12) ? 'Good Morning!' : 'Welcome!';
echo $greeting;

From PHP 5.3, it is possible to leave out the middle part of the ternary operator. In following example, if $name is not empty, its value will be printed. Otherwise Anonymous will be printed.

echo ($name) ? : 'Anonymous';
Where to Head from Here...
Share with Your Peers...

We Value Your Feedback...

We love to hear what you think about this article. Please provide your opinion, suggestions and improvements using following form. Note that submitted feedback is not displayed but we will get back to you if it needs a reply.