PHP Pandas: Forks

← Back to Index

Right now your application follows the sequence of lines that you've placed in your source files. Life isn't like that, though, is it? We don't just blindly follow orders. We make decisions based on the information around us.

In PHP, our information is held within variables. To make decisions based on the value of these variables we can use forks. They fork the flow of our application, changing its path depending on the result of a comparison. In PHP, we call this an if statement.

If

Let's take a look at a basic if statement. I think it might be best if we lead with an example, don't you?

<?php

if (true) {
    echo 'Yey, panda time!';
}

An if statement always begins with an if. Well, I'm sure you'd worked that out. Next we have two sections. The code within the ( rounded ) brackets is the condition. If the condition evaluates to a true value, then the code within the { curly } braces will be executed.

Let's execute this snippet to see what happens.

Yey, panda time!

Awesome! It's always great when it's panda time. The echo statement within the curly braces is executed because the condition evaluates to true. Well, the condition is true, but that still evaluates to a boolean true.

Let's see what happens if we change the condition to something that evaluates to a boolean false. How about this?

<?php

if (false) {
    echo 'Yey, panda time!';
}

Let's go ahead and execute the code one more time.

(nothing)

There we go, nothing happened. The code within our curly braces isn't executed when our condition evaluates to false.

You might be asking yourself why this is useful? Why can't we just add or remove the line of code when we need it? Well, it's because providing simply a boolean doesn't make the if statement very useful. It was just a clean way of explaining how conditions are evaluated as booleans.

Consider the following variation. There's a slight difference, can you spot it?

<?php

$panda = 'Lushui';

if ($panda == 'Lushui') {
    echo 'Yey, panda time!';
}

This time, we're comparing the value of a string variable to another string. Once again, the echo statement will be executed. This is because $panda does equal 'Lushui'. This means that the condition once again evaluates to true.

Let's change the value of $panda to see what happens.

<?php

$panda = 'Pali';

if ($panda == 'Lushui') {
    echo 'Yey, panda time!';
}

We'll execute the code once more.

(nothing)

There we go. This time, $panda does not equal 'Lushui'. This means that the condition will equate to false, and the code within the curly braces (actually, we call this a 'block') will not be executed.

Right now, we're controlling the value of $panda, but what if $panda was set as the result of user input? If we set $panda to whatever our user typed into our application. Perhaps it could be data acquired from another part of a big application. This data would be able to change the flow of our application, allowing sections of code to be executed only under certain conditions. This is when programming gets exciting.

Any statement within the condition will be evaluated. Go ahead and experiment with this basic if statement for a while before moving to the next section. It will be a very important part of your new career in programming.

Else

ELSE!? Else what!? Sorry. It just sounded like one of those dramatic moments in a soap opera. You, know. When someone threatens someone else with a 'or else!'. Actually, else is just another extension to the if statement. Shall we take a closer look?

<?php

$panda = 'Pali';

if ($panda == 'Lushui') {
    echo 'Yey, Lushui time!';
} else {
    echo 'Oh hey there Pali!';
}

The else portion of our if statement functions in a similar fashion to the if portion. The only difference is that else doesn't require a condition. The code within the else curly brackets will be executed only if the condition within the if statement equates to false.

This means that our if statement can now react to both circumstances, whether the condition evaluates to true or false. This is a definite fork. Two different parts of the application can execute depending upon a condition.

Well that was simple, wasn't it? Let's get to the final component of the if statement.

Elseif

Woah! That's both of those words combined! Now things are getting really serious. Right then, you know how this works by now. Let's get started with an example.

<?php

$panda = 'Pali';

if ($panda == 'Lushui') {
    echo 'Yey, Lushui time!';
} elseif ($panda == 'Pali') {
    echo 'Oh hey there Pali!';
} elseif ($panda == 'Jasmina') {
    echo 'Looking pretty Jasmina!';
}

Hey look! More paths! Using the elseif blocks we are able to provide alternate conditions for our fork. PHP will work its way down the list of conditions, and execute the code block for the first one that evaluates to true.

In the above example, we can see that if we were to alter the $panda variable, there are four possible outcomes to our snippet of code. Let's list them for clarity.

  • $panda is Lushui - Yey, Lushui time!
  • $panda is Pali - Oh hey there Pali!
  • $panda is Jasmina - Looking pretty Jasmina!
  • $panda is something else. - (nothing)

If we want to, we can also use else alongside elseif to provide a default execution path for when none of the other conditions match. Let's take a look at an example.

<?php

$panda = _SOMETHING_;

if ($panda == 'Lushui') {
    echo 'Yey, Lushui time!';
} elseif ($panda == 'Pali') {
    echo 'Oh hey there Pali!';
} elseif ($panda == 'Jasmina') {
    echo 'Looking pretty Jasmina!';
} else {
    echo 'Sorry, who are you?';
}

Experiment with the different combinations of if, elseif and else to see how different outcomes of conditions effect the flow of execution within your code. We're starting to become real developers now, can you feel it?

Switch

When you find yourself using many elseif statements to compare the same variable, you're probably going to want to use a switch statement instead. It's a much cleaner and more efficient way of reacting to different values in different ways.

Let's take a look at an example switch statement. We'll start small. First, let's take a look at the switch block.

<?php

switch ($panda) {

}

The switch statement takes a similar shape to that of the if statement. Except this time, it's not a condition that is contained within the curly braces. Instead it's the value that we wish to compare.

Let's add some case statements to the example so we can see how it works.

<?php

$panda = _SOMETHING_;

switch ($panda) {

    case 'Lushui':
        echo 'Yey, Lushui time!';

}

Within the curly braces of our switch statement, we provide our case's. Case's let us compare the value of the variable provided to the switch, and execute lines of code if there is a match.

In the above example, we create a line beginning with the word case. Next, we provide the comparison value followed by a : colon. On the next line(s) we provide the code that we wish to be executed if there is a match.

We can add as many case statements as we like. Here's another example with multiple comparisons.

<?php

$panda = _SOMETHING_;

switch ($panda) {

    case 'Lushui':
        echo 'Yey, Lushui time!';

    case 'Pali':
        echo 'Oh hey there Pali!';

    case 'Jasmina':
        echo 'Looking pretty Jasmina!';

}

Here we can see multiple case statements. Be careful, though! There's a gotcha in the snippet! You see, whichever case statement matches, the code from the other case statements below will also be executed.

This means that if the value of $panda is Lushui then all three echo statements will be executed. This could be really useful if we wanted them to be executed, but right now, we don't! So how can we make sure that only a single echo statement is executed? Simple! We'll take a break or three!

<?php

$panda = _SOMETHING_;

switch ($panda) {

    case 'Lushui':
        echo 'Yey, Lushui time!';
        break;

    case 'Pali':
        echo 'Oh hey there Pali!';
        break;

    case 'Jasmina':
        echo 'Looking pretty Jasmina!';
        break;
}

If we place a break statement on the line after our echo statements, we can stop the execution of the switch statement at that point. The flow of execution will break out of the switch and continue after the final } closing curly brace.

These break statements will also have the same effect on if, elseif and else statements. Break is a keyword that will break the execution of the current fork. It's a useful one to remember!

There's one final thing that's missing from our switch statement. Right now, it's similar to how our elseif statement functioned without the else on the end. So, how do we replicate the functionality with the else? Well it's simple, we must simply provide a default!

Let's change our example, shall we?

<?php

$panda = _SOMETHING_;

switch ($panda) {

    case 'Lushui':
        echo 'Yey, Lushui time!';
        break;

    case 'Pali':
        echo 'Oh hey there Pali!';
        break;

    case 'Jasmina':
        echo 'Looking pretty Jasmina!';
        break;

    default:
        echo 'Sorry, who are you?';

}

The default statement works in a similar fashion to the case statement, except that you don't need to provide a comparison value. The code below the default will be executed if none of the other case statements have matched.

The default statement doesn't require the break because it's the last part of the switch statement. However, if you'd like to add it for clarity, then it won't make a functional difference.

In the next chapter we'll be taking a look at iterators. Get excited! Go on, I dare you!

My books are available online for free to encourage learning. However, if you'd like for me to keep writing, then please consider buying a digital copy over at Leanpub.com.

It's available in PDF, ePub, and Kindle format, and contains a bunch of extras that you won't find on the site. I have a full-time job, and I write my books in my spare time. Please consider buying a copy so that I can continue to write new books from the comfort of my sofa!