3 Branching and Conditionals

Let’s open up our text editor and create a new file starting with “<?php” and save it to a file with a name like branching_example.php or similar.

PHP has some operators, and only a few will be intuitive. When doing math, “+”, “-”, “*“, and”/” probably behave like you’d guess. There’s an operator “%” called “modulo” that is really useful. If you remember remainders, the modulo operator will result in the remainder after division. For example, 7%3 is 1, because 3 goes into 7 twice with 1 as the remainder. 17%4 is also 1, and that’s because 4 goes into 17 four times with 1 as the remainder. Let’s say you have a variable $my_value and you want to see if it’s even or odd. Another way to phrase this is: “does the number have a remainder when divided by 2?” and if the answer is “yes,” that means it’s odd, and if the answer is “no,” that means the number is even. Let’s turn this into code:

<?php

$my_value = 1; // is it odd or even?

if($my_value%2 != 0 ) { // the number has a remainder when divided by two
    print("It is odd!\n");
}
if($my_value%2 == 0 ) { // the number has no remainder when divided by two
    print("It is even!\n");
}

The first thing to note is the double slashes “//” which indicate a comment. You can write comments to clarify things for yourself and others who read your code. If you want to make a multi-line comment, use “/*” and “*/” instead of “//” like this:

<?php 

/*
 * Here is a line
 * Here's another
 * Wow a third line, and it's still a single comment?
 */

You can put asterisks on all the lines of your comment and line them up vertically to make it look better. Some text editors will do this formatting by default, but formatting it like that is not necessary. The “/*” and “*/” parts are all that’s necessary to comment out multiple lines. This is a nice debugging technique.

The second part to note is the if-statement. This lets us check if something is true and do something if it is. Here’s another example:

<?php

$this_variable_is_false = false;

if($this_variable_is_false = true) {
    print("Will this run?\n")
}

So, what do you think? Will that print statement run? Test it out for yourself.

The result might surprise you, but let me explain. In the previous example, the expression inside the if-statement’s parentheses used a single equals sign “=” and we’ve seen that a single equals sign is what you use to assign a value to a variable. The program understands it this way, and will assign true to the variable and then the value is true and the part of the if statement inside the curly braces “{ }” is executed. To actually check if the variable is true, we use a different operator than “=” because we don’t want to assign a value to a variable, we want to compare a value to a variable. Instead of the single equals sign, we’ll use a double equals sign “==” as in the first code example in this chapter. That example also used “!=” which will return true when comparing unlike values, or in other words the values are not equal to each other. Using “=” instead of “==” in if-statements is a potential mistake for beginners that’s quite easy to make.

When a variable contains true or false, it’s called a boolean. This name is an homage to a mathematician, George Boole. If the part of the if-statement in the parentheses evaluates to true, the code in the curly braces executes. Since booleans are true or false, you can write if-statements like this:

<?php 

$my_boolean = true;

if($my_boolean) {
    print("\$my_boolean is true!\n");
}

There are more operators. In the way that “+” and “-” are for adding and subtracting numbers, there are other sorts of operators for doing mathematics with booleans and other data types. Is false plus false, false? According to PHP, false + false is 0. There’s better ways to work with booleans, than “+” and “-” so let’s use them! I’m pleased to introduce “&&” and “||” which can be read as “and” and “or” respectively. And now an example with these operators in use:

<?php 

if(true && true) {
    // code here will run
}

if(true && false) {
    // code here won't run
}

if(true || true) {
    // code here will run
}

if(true || false) {
    // code here will run
}

An if-statement can contain another if-statement, like so:

<?php 

$my_integer = -27;
$my_boolean = true;

if($my_integer < 0) {
    if($my_boolean) {
        // do something
    } 
}

An if-statement within another if-statement can be called a nested if-statement. In some cases, you might want to use an else-statement. A simple if-statement is like saying “do this under this circumstance” whereas an if-else statement is like “do this under this circumstance, otherwise do that instead.”

Sometimes, when I’m grocery shopping, I act like a program. To me, there’s nothing like an avocado. I like avocados, and there’s no replacement in my mind suitable for them… but they’re usually pricey. If they’re too pricey, I just don’t get them. But with fruit, I like berries more than apples, but berries are usually pretty expensive. If berries are on sale, I’ll get berries, otherwise I’ll just get apples. Here’s how that would look as some PHP code:

<?php

if($current_avocado_price < $my_max_avocado_price) {
    // buy some avocados
}

if($blueberries_on_sale) {
    // buy some berries
} else {
    // buy some apples
}

Let’s start tackling a somewhat common interview challenge. Fizzbuzz is a very simple game that works for any number of players. Someone begins counting at 1, the next person increments the number and says the number unless the number is divisible by three or five. If it’s divisible by three, say fizz, if it’s divisible by five, say buzz, if it is divisible by both, say fizzbuzz. Here’s some PHP code that takes a number and prints the appropriate response as if it were playing fizzbuzz:

<?php


//the number we want to test
$number_to_test = 25;

// initialize to false by default before testing
$divisible_by_three = false;
$divisible_by_five = false;

if($number_to_test % 3 == 0) {
    $divisible_by_three = true;
}

if($number_to_test % 5 == 0) {
    $divisible_by_five = true;
}

if($divisible_by_three && $divisible_by_five) {
    print("fizzbuzz\n");
}

if($divisible_by_three == true && $divisible_by_five == false) {
    print("fizz\n");
}

if($divisible_by_three == false && $divisible_by_five == true) {
    print("buzz\n");
}

if($divisible_by_three == false && $divisible_by_five == false) {
    print($number_to_test."\n");
}

Exercises:

  1. Modify the fizzbuzz example to use if-else statements or nested if-statements. Check your edited version for correctness by trying various values (3, 17, 45, 61, &c.) and checking the output for correctness (fizz, 17, fizzbuzz, 61, &c.). As it’s currently written, all six if-statements are checked everytime the program is run. You can make the program more efficient by using if-else-statements and nested if-statements and reducing how many conditions need to be checked. Thinking about efficiency won’t really matter a whole lot here, but if you are one day running a program billions of times, making it run in half the time could save lots of time and money. Unlike math, correctness isn’t enough. Programming challenges can often be solved in multiple ways that are equally correct. Two methods might be correct, but one might be better because it runs in less time or uses less resources.

  2. Using if-statements and the modulo operator, can you write a program that can tell you if a whole number from 1 to 100 is a prime number?