Lesson Weekend

The values of true or false that we have been using in our branching are actually another type of variable, like strings or numbers, which are called booleans. A boolean can only have one of two values - true or false. All conditions inside of the parentheses of an if statement evaluate to booleans. Let's investigate this a little more in the PHP shell.

> $my_boolean = 3 > 1;
> var_dump($my_boolean);
bool(true)

Here, you can see that $my_boolean is of type bool (short for boolean) and its value is true.

> $my_boolean = 1 > 3;
> var_dump($my_boolean);
bool(false)

Now, let's look a little deeper at our address book program from the last lesson, because there's one small problem. What if the user only puts in one or two people and doesn't fill out all the fields? You'll be left with ugly colons on the page with blank space surrounding them!

To fix this, we want to only print an address book entry from our loop if both the name and address fields have been filled out for that entry. Did you hear the "if" in the previous sentence? That means we need branching. Add this if statement to your loop:

foreach ($address_book as $name => $address) {
    if ($name != "") {
        echo "<h3>" . "$name: $address" . "</h3>";
    }
}

This way, the echo statement only gets executed when the if statement is true.

There's another way to write this, though:

foreach ($address_book as $name => $address) {
    if ($name) {
        echo "<h3>" . "$name: $address" . "</h3>";
    }
}

This looks a little weird because name is a string, not a boolean. But in PHP, several values are considered falsy:

  • the number 0
  • an empty string ""
  • the string "0"
  • an array with no elements

Any time you use one of these values in an if statement, it will be treated just like false. And if you use any other value, such as a non-empty string like "duck" or a non-zero number like 31, it will be treated as truthy, the same as true.

So, in our above example, if there is a value inside of our $name variable, then we will print the name and address. But if a name field is not filled out, its value will be an empty string, which is falsy.

To be extra sure, we could check both the name and address:

foreach ($address_book as $name => $address) {
    if ($name && $address) {
        echo "<h3>" . "$name: $address" . "</h3>";
    }
}

Let's do one last exploration of truthiness and falsiness:

> $empty_string = "";
> if ($empty_string) {
    echo "Evaluates to true.";
} else {
    echo "Evaluates to false.";
}
Evaluates to false.

> $new_string = "cat";
> if ($new_string) {
    echo "Evaluates to true.";
} else {
    echo "Evaluates to false.";
}
Evaluates to true.

> $my_number = 13;
> if ($my_number) {
    echo "Evaluates to true.";
} else {
    echo "Evaluates to false.";
}
Evaluates to true.

Get the idea?