Beginner PHP Chapter 4 – Conditional Statements

(Note: Originally this chapter was meant to cover both conditional and loop statements. Due to the length of the post, I’ve decided to split it into two chapters.)

In the previous chapters, we’ve covered variables, functions, and operators. We’ve also touched slightly on conditional statements. In this chapter, I’m going to cover the rest of conditional statements. Like the elements that you’ve learned in the previous chapters, conditional statements are basic building blocks that enable you to build powerful scripts. Once you master these, you’ll be able to create complex and sophisticated systems with just a few lines of code. But first let’s get to know this statement type.

Conditional Statements

What are conditional statements?

In chapter 3, we touched a little bit on conditional statements when we covered conditional operators, as the two can’t be separated. A conditional statement is a block of code that is executed if certain requirements are met. Using these will allow you to achieve greater sophistication within your codes, as it allows your script to react to current conditions.

What type of conditional statements are there?

Conditional statements can be divided into four major keywords, if, else, elseif, and switch. There are also three minor keywords that are used with the ’switch’ keyword, which are case, default, and break.

Why should I use conditional statements?

And this is where I go crazy with the examples. The ‘if’ keyword is pretty simple to explain. Let’s say you’re driving. If you’re low on gas, stop at a station and refill. Easy, no? So let’s give another example that’s a bit more script-related. Let’s say you’re asking a user to enter his email address. If the email address space is empty when the user submits the form, let him know that he/she forgot about it.

Next is the ‘else’ keyword. I’ll reuse the previous two examples so you can better understand. Let’s say you DO stop at that gas station. We can use an ‘if’ statement that goes something like this:

If you have cash, pay using cash.

The problem with this is that if you DON’T have cash, nothing happens. Even worse, you’ll just continue on with your action, which would result in you filling up without paying. Not good. Now let’s add an ‘else’ to that:

If you have cash, pay using cash. Else, pay using your credit card.

Much better. As you can see, the end result is that you end up paying for the gas one way or the other. Which tends to help you not get arrested. How about the user with the missing email address, then? Let’s look at it with just the ‘if’ keyword:

If the space for email address is empty, alert the user.

Can you predict the problem here? Your script will alert the user, but will also continue to process the form. Even if this doesn’t result in problems in your code, you’re left with no email address to contact him/her with. Let’s add an ‘else’ keyword into that.

If the space for email address is empty, alert the user. Else, continue processing the form.

Now, if the user doesn’t enter his/her email address, the script will stop processing the form. You’ll find that when you create forms for user input, these kind of conditions will ensure that your user is more likely to fill the form up properly, which will greatly benefit both you and him/her.

Now let’s move on to the ‘elseif’ keyword. Some of you have probably surmised that since the word is basically ‘else’ and ‘if’ mashed together, it should function like both those keywords combined, and you’d be right about that. The ‘elseif’ keyword allows you to expand a conditional statement by adding a third possible outcome, or a fourth, or as many as you want. Let’s head back to our gas station example then. This is where we were:

If you have cash, pay using cash. Else, pay using your credit card.

Let’s assume you don’t have any cash, and you don’t have your credit cards with you either. Talk about bad planning. So when it comes time for me to pay, the following would happen: you’d check if you had cash, and find out that you have none. Then you’d reach for your credit card. At that point, you’d realise that you don’t have your card with you. What you DO have, however, is a problem. And a rather annoyed gas station attendant. So let’s add a third possiblity to this:

If you have cash, pay using cash. Elseif you have your credit card, pay using your credit card. Else, withdraw some cash using your ATM card and pay.

You’ll notice that the ‘elseif’ keyword comes before the ‘else’ keyword. This is because ‘else’ is the what the script considers as a Plan-Z, something to use when nothing else works out. Thus, logically, it is written at the end of the conditional block.

And last but not least, is the ’switch’ keyword. This keyword is slightly different from the others, because it requires you to have a variable beforehand. So to explain this, I’m going to use a different situation. Let’s say you’re a bartender at a fancy hotel in Vegas (hey, why dream small?). You get an order for a drink. Naturally, the first thing that you’d do is get a glass ready. But as any self-respecting bartender would tell you, you can’t just pick ANY glass. What did the customer order? If it’s a martini, get a martini glass. If it was champagne, get a flute. So the type of glass you reach for, depends on the order.

In that scenario, the order is your variable. You’d have a bunch of options beforehand, along with a default choice that would happen if the order didn’t fit any category (maybe he just wanted plain water?). That’s where the ‘default’ keyword comes in. The choices you are prepared for beforehand (e.g. martini, champagne, vodka, scotch, etc) are defined using the ‘case’ keyword. And finally, the ‘break’ keyword is used to separate each choice, so we don’t end up reaching for all the glasses for that one drink. You’ll be able to better understand this structure by looking at the code samples below, so don’t worry if you haven’t got it yet.

How do I write conditional statements?

Note that for all the conditional statements, and also for the loop statements later on, you’ll see that there are two major ways of writing them. One uses curly brackets, while the other uses a colon (:) and a type of ‘end’ syntax to end a block. The latter is popularly known as the alternative syntax. Both ways will work, both ways have their pros and cons. Deciding which one to use when writing your scripts is entirely up to you, so choose the one you’re more comfortable with.

Let’s start with the ‘if’ keyword. I’ll reuse the previous example to make things clearer. First up is the old-school, or standard syntax:


<!--?php<br /-->
if($gas=='low'){
	stop_at_petrol_station();
	refill_gas();
};

?>

And next is the alternative syntax for writing the same thing.


<!--?php<br /-->
if($gas=='low'):
	stop_at_petrol_station();
	refill_gas();
endif;

?>

There are really only two points of difference between the two syntaxes, and they’re both at the curly brackets. The opening curly bracket is replaced by a colon (:), while the closing curly bracket is replaced by the keyword ‘endif’. How about our second example? Using the standard syntax:


<!--?php<br /-->
if($email_address==''){
	alert_user('It looks like you forgot to enter your email address');
};

?>

And using the alternate syntax:


<!--?php<br /-->
if($email_address==''):
	alert_user('It looks like you forgot to enter your email address');
endif;

?>

Now let’s move on to the else keyword. Starting with our gas station example, here are both syntaxes:


<!--?php<br /-->
if($got_cash=='yes'){
	$payment_method = 'cash';
} else {
	$payment_method = 'credit card';
};

if($got_cash=='yes'):
	$payment_method = 'cash';
else:
	$payment_method = 'credit card';
endif;

?>

Pay careful attention to the differences between the two. The curly brackets are all gone in the alternative syntax, and there are colons where the opening curly brackets used to be. Finally, the last curly bracket is replaced by the ‘endif’ keyword. Another element that you will want to pay attention to is the usage of semicolons and colons in your blocks. Make sure you don’t mix the two up, as it is likely to cause your script to break.

Now let’s move on to our second example, the user with the missing email address:


<!--?php<br /-->
if($email_address==''){
	alert_user('It looks like you forgot to enter your email address');
} else {
	continue_processing_form();
};

if($email_address==''):
	alert_user('It looks like you forgot to enter your email address');
else:
	continue_processing_form();
endif;

?>

And now our ‘elseif’ keyword.


<!--?php<br /-->
if($got_cash=='yes'){
	$payment_method = 'cash';
} elseif ($got_credit_card=='yes'){
	$payment_method = 'credit_card';
} else {
	withdraw_money();
};

if($got_cash=='yes'):
	$payment_method = 'cash';
elseif ($got_credit_card=='yes'):
	$payment_method = 'credit card';
else:
	withdraw_money();
endif;

?>

Note: For the standard syntax, ‘elseif’ can also be written as ‘else if’.

Now for the ’switch’ keyword. As you’ve probably noticed, the ‘if’, ‘else’, and ‘elseif’ keywords all fit into the same structure. The ’switch’ keyword, however, uses a different structure entirely. Here’s an example:


<!--?php<br /-->
switch($variable){
	case 'valueA':
		//Any code here is executed if $variable's value is 'valueA'.
		break;
	case 'valueB':
		//Any code here is executed if $variable's value is 'valueB'.
		break;
	default:
		//Any code here is executed if $variable's value is neither 'valueA' nor 'valueB'.
};

?>

The biggest difference between the ‘if’ structure and the ’switch’ structure is that the ’switch’ structure only looks at possible values for a variable. The ‘if’ structure, along with ‘else’ and ‘elseif’, is infinitely more flexible and powerful (in my opinion, anyway), but since programmers tend to use both of these structures interchangeably, I’d recommend familliarising yourself with both types.

Like it’s ‘if’ counterpart, the ’switch’ structure also has an alternative syntax. Here it is:


<!--?php<br /-->
switch($variable):
	case 'valueA':
		//Any code here is executed if $variable's value is 'valueA'.
		break;
	case 'valueB':
		//Any code here is executed if $variable's value is 'valueB'.
		break;
	default:
		//Any code here is executed if $variable's value is neither 'valueA' nor 'valueB'.
endswitch;

?>

The differences are pretty much the same as the other alternative syntaxes: the opening curly bracket is replaced by a colon, and the closing curly bracket is replaced by an ‘endswitch’ keyword. Like any other time you use the alternate syntax, be aware of where your colons and semicolons are supposed to go. Now let’s try that using our bartender example:


<!--?php<br /-->
switch($order):
	case 'martini':
		$glass = 'martini glass';
		break;
	case 'vodka':
		$glass = 'vodka glass';
		break;
	case 'champagne':
		$glass = 'champagne flute';
		break;
	default:
		$glass = 'normal glass';
endswitch;

?>

So if the bartender receives an order for a martini, vodka, or champagne, he brings out the appropriate glass. Otherwise, he just takes a normal glass. You’ve probably realised it by now, but the ‘default’ keyword pretty much acts the same way as the ‘else’ keyword. It provides the script with a last resort to turn to when all the previous options can’t be used.

Note the ‘break’ keyword in between each ‘case’ keyword. The ‘break’ keyword ensures that the script won’t execute the next case’s codes, and the next one, and so on. For example, if we took out the ‘break’ keywords, and ran the same script, the following would happen:

If the bartender receives an order for something other than a martini, vodka, and champagne, he will take a normal glass.
If the bartender receives an order for champagne, he will take a champagne flute, and then take a normal glass.
If the bartender receives an order for a vodka, he will take a vodka glass, then take a champagne flute, then take a normal glass.
If the bartender receives an order for a martini, he will take a martini glass, then take a vodka glass, then take a champagne flute, then take a normal glass.

The ‘break’ keyword allows us to structure the flow by putting blockades in between each case. Note that there may be times when you’d rather not have the ‘break’ keyword there. A simple example of this:


<!--?php<br /-->
switch($level){
	case 'level 1':
		finish_level_1();
	case 'level 2':
		finish_level_2();
	case 'level 3':
		finish_level_3();
	case 'all finished':
		get_prize();
};

?>

If the value of $level was ‘level 1′, all four functions would be called in the order that they are listed. If the variable’s value is ‘level 2′, then it would start from calling ‘finish_level_2()’, and then working it’s way down from there. And so on and so forth. For 90% of the time, you’ll probably want to use the ‘break’ keyword to separate your cases, but it’s worth knowing about this stair-step kind of technique.

And that about wraps it up for the conditional statements. Like all other PHP coding elements, if you’re not sure about whether a certain combination of elements or a certain method will work, the easiest way is to try it out for yourself. PHP will be only too happy to let you know if there’s an error :).

Of course, in our next chapter, I’ll be covering loop statements. I’ll also be covering how you can combine conditional and loop statements within and around each other to create massively useful code blocks. Sounds confusing? Trust me, it’s pretty simple once you understand the basics. Till then, I’d love to hear what you have to say. If you have any questions, comments, or feedback about how I can improve my tutorials, please let me know in the comments. Thanks!

Other posts in the series

  1. Beginner PHP Chapter 4 - Conditional Statements (This post) -
  2. Beginner PHP Chapter 3 - Operators -
  3. Beginner PHP Chapter 2 &ndash; Functions and Variables -
  4. Beginner PHP Chapter 1 &ndash; The Meet n&rsquo; Greet -
Posted On:
Post Date
23rd July 10
Category:
Post Category
Tags
Post Tags
Comments
Post Comments
None yet