This course will become read-only in the near future. Tell us at community.p2pu.org if that is a problem.

The if, the else, and the else if


if statements are one of the ways the desicion making process of programming works.
if you're unfamiliar with an if..else statement, think about this:


if you are hungry, you eat. else you don't eat.


For those people who are more logical thinkers, here's what the syntax looks like:

<?

if (condition == true)
{
    // if my condition is true, this happens.
}
else
{
    // if my condition is false, this happens.
}

?>

Here's how the if/else conditional statement works:
Once a condition is true, it executes everything in between the two curly brackets, and ignores all other if/elseif/if statements connected to it.
We'll get to else if statements soon.

Your task:
To follow along, and do what I do for the rest of this class.

Open a new .php file, save it as if_else.php
Write the open syntax, and declare a string variable with the value of your first name.
Close syntax.

What we should have so far is:

<?

$name = "Kalob"; // I'll use my own firstname for this class

?>

Now we're going to create our first if statement, with an else attached to it.
Note: you can have if statements without the else attached.

Here's what an if statement will look like, and we use comparison and logical operators here. We'll start with a comparison operator.
Note: the assignment operator = is not the same as the == operator. You use = to assign variables, and use == to compare.

<?

$name = "Kalob";
if($name == "Kalob")
{
    echo "My name is " . $name;
}

?>

if you haven't done so already, write this out, but but feel free to rename the variable (remember: alphanumeric and underscores only), and change the variable value to your own First name.
Once you've done this, upload if_else.php to your server, or test it on your local server, and see what shows up.
if everything went well, your page should display:


My name is Kalob


Now, we're going to add another variable, and an else statement. Follow my lead (type this out as well).

<?

$name = "Kalob"; // this is your first name
$friend = "Jai"; // choose a friend, can be any name!
if($name == "Jai")
{
    echo "My name is " . $friend; // this won't execute, because $name is "Kalob", and it is not "Jai"
}
else
{
    echo "My name is not Jai, it is " .$name; // This will display, because the if statement above this was incorrect.
}

?>

if you test this out right now, it will display:


My name is not Jai, it is Kalob


So because the if statement was wrong, PHP will skip that chunk of code under it, and go to the else statement.
Try this:
Delete the entire else statement, and test if_else.php, by uploading or testing on your local server. What happens?
..
..
Nothing should happen. Because we left out the else statement, there is nothing to execute. The if statement was incorrect, and with nothing else to catch it, PHP just ignores it.
Ok, add the else statement back in. (edit->undo will become a new best friend)

if you go back to the Operators class and look at comparison operators, you'll see we have a few choices. if you're brand new to programming, this next part might seem slightly confusing, but bare with me.
We used the == operator in the if condition. But what if we changed the == to a != instead? Let's do that..

<?

$name = "Kalob"; // this is your first name
$friend = "Jai"; // choose a friend, can be any name!
if($name != "Jai") // we changed the operator
{
    echo "My name is " . $name; // we changed this sentence
}
else
{
    echo "My name is Jai"; // we changed this sentence
}

?>

Test the page. Notice it changed? That's because the not operator (!=) was true. Let's read this in english:
if my name is not Jai, echo "My name is Kalob".
That's a true statement, it's correct, it's not false at all! My name is not Jai, it's Kalob.
We can also use numbers. I'll give you a quick example of a numerical condition.

<?

$age = 20;
if($age>=21)
{
    echo "I'm allows to drink in the states!";
}
else
{
    echo "I can't drink yet, I'm only " . $age . " years old";
}

?>

In english:
if age is greater than or equal to 21, Im allowed to drink. Otherwise, I cannot drink alcohol.
Take the next ten minutes, and just play with these operators and conditions. Make a few on your own even.

 



K, now that you did some exploring on your own... how did it go? if you think you're ready for a little more then continue on. (I made an if statement =D ) But if you had some trouble with this, definitely send me a message with your code, and I'll help you out.

So right now, we've made PHP make a decision. if the first choice is true, it executes the code under it. Otherwise it will do whatever is in the else statement. We can add to this!
We take an if and take an else, and mix them! Yup, we get an elseif statement. And if you look at it, it should just be another if statement, shouldn't it? Yes, yes it should.
With an elseif statement, we can add another conidition, and check if this is true. Let's go back to our example with the names. Pay close attention, I modified this a little bit.

<?

$name = "Kalob";
$friend = "Jai";
if($name == "Jai") // we changed the operator, again
{
    echo "My name is Jai";
}
elseif($name == "Kalob") // we are adding the elseif in
{
    echo "My name is Kalob";
}
else
{
    echo "My name is not Kalob or Jai"; // we changed this sentence
}

?>

if you haven't modified your code, definitely do that.

Note: if you're feeling adventurous at any given time, stop reading this class for a few minutes and trial & error your scripts. I find that to be the best way to learn.

Your page should say "My name is Kalob". Optionally, we can use a logical operator instead of writing an entire new chunk of code.

<?

$name = "Kalob";
$friend = "Jai";
if($name == "Jai" || $name == "Kalob") // we use two == operators, and a the or logical operator.
{
    echo "My name is " . $name;
}
else
{
    echo "My name is not Kalob or Jai"; // we changed this sentence
}

?>

In english:
if my name is Jai OR my name is Kalob, echo "My name is $name". Otherwise, echo that my name is not Jai or Kalob.

With PHP we do not have to use curly brackets to enclose our code we want to execute, can just indent and PHP will find where to stop the condition. This is up to you, but I highly recommend using curly brackets until you find your own style of coding - this way everything stays neat and easy to read.

One more task:
Spend another 15 minutes manipulating our example code, but use different comparison and logical operators.
This is crucial, because in the future we use a lot of conditional statements.

Any questions or if you need help, send me a message.

Task Discussion


  • Tynanh   March 18, 2013, 2:22 a.m.

    Played around alot with if statements!

    check out a little program I made using if statements, I also posted all the code to the page so it can be viewed. (added lots of comments)

    practice_if.php

  • MF   Oct. 4, 2012, 2:33 p.m.

    Hi,

    Link to my exersise:

    http://www.marianaphp.tit4tat.co.uk/if_else.php

    http://www.marianaphp.tit4tat.co.uk/if_else_test.php

    Code sample:

    <html>
    <body>


        <?

            $name = "Mariana";
            $friend = "Dominic";

            if($name == "Domnic" || $name == "Olaf")
            {
                echo "My name is " . $name. "<br/>";
            }
            else
            {
                echo "Who are you?<br/>"; // we changed this sentence
            }

            if($name == "Mariana" && $friend == "Dominic")
            {
                echo "Hello fantich&young!<br/>";
            }
            else
            {
                echo "Who are you?<br/>";
            }

    $name = "member";
    $age = 21;

    if($age>=21 && $name == "member" && $friend == "Dominic")
    {
    echo "Wellcome back!<br/>";
    }
    else
    {
    echo "You are intruder!<br/>";
    }

    if($age<21 || $name == "member" && $friend != "Dominic")
    {
    echo "Wellcome back!";
    }
    else
    {
    echo "You are intruder!<br/>";
    }

    if($age>=21 || $name != "member" || $friend != "Dominic")
    {
    echo "Wellcome back!";
    }
    else
    {
    echo "You are intruder!<br/>";
    }

    ?>

  • Asier Iturralde Sarasola   April 13, 2012, 1:09 p.m.

    Here is the code of my if statement.