Operators

You can find a full list of operators and their order of precedence in the manual.

They are all fairly self-explanatory. The most common ones are:

Math:

+ and - (add and subtract)
++ and -- (increment and decrement)
. (concatenate - for splicing strings)
*, /, and % (multiply, divide and modulus, aka. remainder)
^ (exponent)

Comparisons:

<, >, <=, >= (less than, greater than, less than or equal to, greater than or equal to)
==, != (equal to, notequal to – non-type specific, so 1 == '1' evaluates to true)
===, !== (same as, not same as – is type specific, so 1 === '1' evaluates to false)

Logic:

! (not - flips a boolean) &&, || (and, or)
?: (ternary)
?? (null coalescing)

We’ll come back to the ternary and null coalescing operators when we get to some code that needs them.

Flow

Flow is all about “what happens next”. Ordinarily, a program moves from beginning to end, one statement to the next, in the order they are given. But at certain points, that ordinary sequence needs to change in order to accomplish the task we are looking to complete. Let’s take a look at the most common of these.

1. We call a function.

The initials exercise we did is a good example of this. Recall:

function getMyInitials(string $name): string
{
    $explodedName = explode(" ", $name);
    ...
    return $initials;
}

echo getMyInitials(Caspar Green);

All but the last line of this program are defining the callable variable getMyInitials(). Nothing actually executes until we get to the last line. At that point, the last line calls the function, which is like putting a bookmark at the end of the echo command while it executes the code, in order, between the brackets above, then returns to the bookmark after echo and sends the returned value (‘CG’) to the screen.

So with functions we control the flow of the program by pausing the flow to insert that function’s code at the point where the function is called. The power of this is, once defined, we can re-use that function’s code, inserting it as many times as we want, whenever and wherever we want, without having to rewrite it every time we want to use it.

2. We repeat a portion of code in a loop.

PHP gives us several ways of doing this. The most common is the foreach() loop, and is typically used with arrays to perform the same thing using each item in the array in sequence:

$foods = ['apples', 'bananas', 'cookies'];
foreach ($foods as $food) {
    echo 'I love ' . $food . '.';
}

repeats the same echo command as long as there are still items in the array.

The second common loop is the for loop. Here’s an example:

for ($index = 1; $index <= 10; $index ++) {
    echo $index;
}

In the parentheses, we first set up a variable with an initial value. Then we define the comparison that must remain true for the loop to keep looping. Finally, we define what should happen after the completion of each time through the loop. In this case we define an index with an initial value of 1. We want to continue to loop as long as that index variable remains less than or equal to 10. And after each time completing the code we want to increment the index by 1. The result is that numbers 1–10 are printed to the screen in sequence.

The third common loop is the while loop:

$x = 0;
while ($x !== 10) {
    echo $x;
    $x ++;
}

In this loop, the code inside the brackets will repeat so long as the condition in the parentheses remains true. The first time we get to the parentheses, $x is 0, which is not the same as 10 (evaluates true) so the code in the loop executes, and continues to execute until $x is 10. When $x is 10, the !== 10 evaluates to false, and the code inside the loop isn’t executed. So we get numbers 0–9 echoed out to the screen.

So why would you use for rather than while?

The for loop will always execute the code inside the loop once. The conditions are set as the loop is being entered, the code executes, and then the conditions are updated and checked. Depending on what the conditions are before the while loop, it may never execute at all. If in the above, $x = 10 at the beginning instead of 0, the whole thing would get skipped.

3. Branching

The last main flow control is doing one thing, given one criteria, and doing a different thing in response to a different criteria. In other words, an “if … then” situation. Enter the ifelseifelse keywords.

if ('apple' === $myFood) {
    echo 'I have some fruit.';
} elseif ('cookie' === $myFood) {
    echo 'I have some dessert.';
} else {
    echo 'I'm not sure what kind of food I have.';
}

In each of these cases, the code between any given set of brackets executes only when the condition in parentheses evaluates true, AND only the first of the true conditions will be executed should more than one be true. (There can be as many elseifs as you like.) When none of the conditions is true the code in the else brackets gets executed.

Note also, you don’t need to have an elseif or an else.

if ('apple' === $myFood) {
    echo 'I have some fruit';
}

will run the contents of the bracket or not depending on what $myFood is and move on.

(I’ll also mention that you might come across another way of branching called a switchcase branch. This is essentially a shorthand way of declaring a bunch of elseifs. Suffice it to say here that if you have so many elseifs that you need a shorthand to get them all in, you’re probably better off re-thinking your program logic. So, except in rare cases, avoid these.)

One last thing that often trips up beginners.

= is for assigning a value to a variable. $x = 4 is declaring that $x now equals 4. It will always be true, because you are declaring that it is the case. So

if ( $x = 4 ) {
    // do something
}

will always do something.

When comparing to see “if $x is equal to 4?” for purposes of branching or checking a loop condition, use either == (“Is $x equivalent to 4?”) or === (“Is $x the same as 4?”). The more specific you can be the better, so look to use === whenever possible.

Assignment

(Hat tip for this exercise to Dave Guymon.)

A trick to determine whether or not a number is divisible by three is to add all of the digits in the number together and to divide the resulting sum by three. If there is no remainder from dividing the sum by three, then the original number is divisible by three as well.

Write a function that, given a series of numbers as a string, will determine if the number represented by the string is divisible by three. Return true if so; otherwise return false.

You can expect any input will be a string representing a value greater than 0.

Here’s your starting template:

function isThreebee(string $number): bool
{
    // your solution here.
}

echo isThreebee("123"); // should return true
echo isThreebee("8409"); // should return true
echo isThreebee("7"); // should return false
echo isThreebee("102"); // should return true
// add a couple of your own test inputs here