PHP Lessons Part 3: Conditional Statements

by
Guest-GS

Today we will have a look at what Conditional Statements are.

Conditional Statements allow you to perform different kinds of actions based on a given condition. It can either return true or false.

A little Non-Programming example to give you an idea of Conditional Statement Below:

Let’s consider a guy named John, is 16 years old and wants to go to a casino. Unfortunately, casinos doesn’t allow Minors.

So basicaly, the condition is:

If John is less than 18 years old, then don’t let him inside the casino, else, let him in.

Now there are two words that are always used in PHP Conditional Statement. They are “IF” and “ELSE”. Before going on, you should know we are using caps here for emphasis. When using these keywords in code, they are lowercase! PHP is case-sensitive. “IF” and “if” are different things for PHP. Use “if” in code.

IF…ELSE conditions

Very simply, in php, that conditional statement is written like this:

<?php

if($john_age < 18){
	//Condition: John is less than 18 is true so do something to prevent him from getting in
}else{
	//Condition is false - John is 18 or older, let the guy in
}

?>

Note, we are using the variable $john_age here. This is just an example. If this was done in the real world, we’d probably call that variable $person_age instead of pinpointing John. Variables are general placeholders after all. Here, we use $john_age because our code deals with only John. Ain’t he special? ๐Ÿ˜€

What you just saw above is an example of what we call a “block” of statement. Whatever is between { and } is called the block contents. If the { and } come after IF, we say it’s the IF block. The one coming after ELSE is the ELSE block. Those braces { and } are used to determine where a block starts and where it ends.

With that code above, considering John to be 16 years old, the IF block gets executed. Whatever code is in this block gets executed.

Two slashes are comments, remember? Those are just notes for the programmer, and would be ignored by PHP. We put our condition statement between the brackets which is right after the word if and we put the code to be executed between the two braces { and }.

Some good things to remember:

  • We use an IF statement if we want a single check. If the condition is false, we don’t do anything, but proceed. That is, if the condition for the IF statement returns a false
  • We use an IF…ELSE Statement to see if the condition is true, and execute some code. If the condition is false, we execute another piece of code. It’s like a decision.

Also, when IF…ELSE is used, only one block would be executed at any one code run. Both blocks cannot be executed one after the other. I’ll illustrate my point using the casino example: at any one time, you can’t both let John in, and at the same time prevent him from coming in. It won’t make sense. Either you let him in, or you keep him out. Same for the IF…ELSE statement. Either the condition is true, and the IF block is executed, or the condition is false and the ELSE block gets executed, but not both.

Now, let’s have a closer look at how we can write the conditional Statement for the John example i gave you above. Remember than John 16 years old and thus we can’t grant him access and also, remember that we can use Variables to assign a string or value to that variable. Our PHP Condition Statement, in a better and more complex form will look like this:

<?php

$john_age = '16';
$required_age = '18';

if($john_age >= $required_age){
	//John is 18 or older (Required Age)? No. The condition $john_age > $required_age would return false.
        //This block WON'T get executed. We jump to the ELSE part since the condition is false
	echo "Ok, get in";
}else{
	//If the condition above returns false, execute this part, so we do it:
	echo "You are too young to enter!";
}

?>

If we run this code, we would see “You are too young to enter”.

As a general syntax:

<?php

if (condition goes here)
{
        //Do these codes if condition is true
}else{
        //Do those conditions when condition is false
}

?>

Ok, we know how to perform a basic if and else statement. Now let’s have a look at IF…ELSEIF…ELSE

IF…ELSEIF…ELSE conditions

The syntax looks like this:

if(condition1){
	//execute those codes if condition1 is true

}elseif(condition2){
	//execute those codes if condition1 is false, but condition2 turns out to be true

}else{
	//execute those codes if both conditions 1 and 2 return false
}

Below is an example of how it works:

John is 16. The required age to get in a casino is 18. But, there exists a Game Club by the casino, where minors can enter, but only minors accompanied by their parents. Let’s assume John is accompanied by his parents.

Quite a lot of conditions to check huh? Let’s enumerate them for clarity:

  • Age is less than 18
  • Age is 18 or more
  • Accompanied by parent
  • Not Accompanied by parent
<?php

$john_age = '16';
$required_age = '18';
$parent_here = true; //we are using a Boolean here. John is accompanied.

if($john_age >= $required_age){
	//Person is older than Required Age of 18? Let him in
	echo "Ok, you are allowed to enter";

}elseif($john_age <  $required_age && $parent_here == true){
	//Person is younger than 18, but have their parents with them, let them in the Game Club
	echo "You are allowed to enter the Game Club";

}else{
	//Person is younger than 18 and is not accompanied by parent, so deny access
	echo "You are too young to enter";
}
?>

Now if you run this code, you will still get “You are allowed to enter the Game Club”. Both conditions of the ELSEIF block were satisfied. Note the use of the AND operator, the &&.

We can also write one-line condition checks using the “ternary” operator, but we’ll keep that for a bit later. For now, we keep with the IF…ELSEIF…ELSE parts. Let’s see how you can nest conditions. Again with our guy named John:

<?php

//setting some variables
$john_age = '16';
$required_age = '18';
$john_gender = 'male';

if ($john_age > $required_age){

        if ($john_gender == 'male'){
             echo "Gentleman, you can get enter";

        }else{
             echo "Miss, you can enter";
        }

}
else{
        echo "You are too young to enter";
}

?>

What you saw above is an example of nesting of a condition block inside another condition block. Here, we have an IF…ELSE block nested inside another IF…ELSE block. We might call those the inner and outer condition blocks if you want. Nested condition blocks are used to conduct further checks after one condition has proved to be true. Of course, you can also nest conditions in the ELSEIF block or ELSE block if you ever need some. I could also have written the above code in separate IF blocks:

If (age >= 18 && gender == ‘male’), if (age >= 18 && gender == ‘female’), if (age < 18 && gender == ‘male’), if (age < 18 && gender == ‘female’)

The last two would be the ELSE part above: “You are too young to enter”. But it is much simpler to just group them all together.

Note, in real world scenarios, there would only be 2 outcomes for gender: male or not male. It could be female or not female too if you prefer. But usually, we won’t be having male and female. The NOT operator would cater for the remaining one. Therefore, the else part is in fact if ($john_gender != “male”) or maybe if ($john_gender != “female”), depending on what you prefer.

Got enough of conditions yet? There is still one which we use, and it’s not IF…ELSEIF…ELSE type. We call it, the SWITCH condition.

SWITCH condition

What happens when you have a lot of simple comparisons to make? By simple comparisons, I mean the == sign. With SWITCH, you can’t use the other comparisons like > and < for example.

Say, if ($i == 2), if ($i == 3), if ($i == 4), etc… That’s a lot of IF’s! We then use the SWITCH statement which makes grouping easier. Let’s see:

<?php

switch ($i){

        case 2:
        //if value of $i is 2, do something then,
      break;

        case 3:
        //if $i is 3, do another thing then,
        break;

        case 4:
        //if $i is 4, do yet another thing then,
        break;

       default:
       //if $i is something else, do this.
       //No need for "break;" here since this block usually executes last
       //The switch would break anyway, after it executes
}

?>

Now what does this code do? It will do the comparison checks and execute the appropriate code. But I want you to pay attention to the “break;” keyword. This is new for you. It simply means that, when PHP reaches that keyword after executing, it will stop processing the block, and jump out of it. We are using it here, to indicate the end of a particular case block.

What happens if you don’t put “break;” at the end of a case block? PHP jumps to the next case. Say we hadn’t put “break;” for case 3. PHP would execute case 3, and jump on to case 4 and execute. Be careful, unless this is exactly what you want PHP to do, as in this example:

switch ($i){

        case 2:
        case 3:
        //do something then,
        echo "test";
        break;

        case 4:
        //do yet another thing then,
        break;

       default:
       //if nothing fits
}

Now, PHP would execute that echo “test”; part if ever variable $i has value 2 or 3. If it has value 4, it’ll execute case 4. If it has another value, it’ll execute the default part.

Ok, I promise, this is the last part of this lesson: ternary operator! These are quite difficult to understand for beginners, so pay attention

Ternary Operator

The ternary operator, which is an interrogation symbol – ?, is used for one-line conditions, usually a one-line IF…ELSE condition. However, it can make code more difficult to understand if abused. So use it only when you really must.

Back to John:

<?php

$john_age = 16;
$required_age = 18;

if(john_age > $required_age){
      echo "You can enter";

}else{
     echo "You cannot enter";
}

?>

in ternary form, this would be:

<?php

echo ( ($john_age > $required_age) ? "You can enter" : "You cannot enter" );

?>

Update: Thanks to Stiofan for pointing out a mistake in the above snippet.

You got that? Kind of tough on the eyes right? That is why I said, avoid if you can! ๐Ÿ˜€ The general syntax is as follows:

if (condition here) ? (do this if condition is true) : (else do this)

Note the use of the ? operator and the : symbol as separator.

Long lesson over! You can breath now. We are at the end. This lesson was a bit long, so re-read it if you can’t understand something on your first read. If you have any questions, comment box is below. For further reference, please check the PHP Manual.

This article was contributed by Tipa of Mu-Anime

[seriesposts title=”PHP Lessons” titletag=h3 listtype=ul orderby=date name=”PHP Lessons” ]

  • stiofan

    if ($john_age > $required_age) ? echo “You can enter” : echo “You cannot enter”;

    this is not correct??? well it dont run on my server?

  • InF

    It seems we have made an error… Use it like this:

    echo ( ($john_age > $required_age) ? "You can enter" : "You cannot enter");