Menu Close

Articles

PHP: Control flow

A PHP script is built out of a series of statements. A statement can be an assignment, a function call, a loop or a conditional. Usually a statement end with a semicolon unless is the last statement before the closing tag: ?>. In addition, statements can be encapsulated into groups by using curly braces: {…}.

Conditional: “if”

This statement is also call “decision” statement. It uses a logical conditional expression to make a decision about execution of next statement. It has two branches: “true” branch and “false” branch.

Notes:

  • Condition is enclosed in round parenthesis (…)
  • The second branch is optional. 

Example:

output:

Note: In the example above make $a = $b, and will force next condition $a == $b to be true. So “else” condition will never happen. If you modify the program and make $b <= $a, then you get: “unexpected” output.

Ladder Statement: “else-if”

Instead of nesting multiple if/else statement, you can create a multi-path statement using “elseif” keyword. This is called “ladder” and is common in many computer languages:
Example:

Alternative syntax: “if”

As incredible as it sounds, PHP has an alternative syntax for block statements. It goes like this: Instead of using {…} to create a block, you can use “:” and end of block keyword: “endif”. 

Note: The two syntax alternatives can not be combined. If you try, PHP compiler should fail.

Ternary Operator: “?”

As an alternative to “if” statement in expressions you can use a special operator “?” that can evaluate a condition and produce one result or another, depending on condition logical value: true or false.

Example:

Loop: “while”

To create a repetitive block of code we use “while” keyword. This evaluate a condition and execute next block, several times until the condition become: false. If the condition is false in the first place the block is never executed and therefore “wile” loop behave like “if” statement in this case.

Example:

Loop: “do..while”

Sometimes we need to execute a block, then decide if the block can finish or we need to repeat. In this case we start a loop using keyword: “do” and evaluate condition after block end using “while”. This way the block is executed at least once.

Example:

Note: The alternative syntax does not work for “do..while” statement.

Loop: “for”

This loop is controlled by a variable and a condition. Usually the variable is incremented using operator “++” for each iteration. This statement uses an expression pattern easy to grok, created with 3 parts: (declaration; condition; increment). In PHP any of these parts is optional.

Example:

Note: In previous example, alternative syntax is not using a condition in “for” expression. So we use two semi-columns instead of one: “;;”. Then we use “if” statement and “break” to interrupt the loop.

Selector: “switch”

The switch statement is a multi-path, value based selector. That means we use one value and we create a multiple cases for possible values. Each value can create a new logical path. There is a special case when no value is found then “default” case is executed.

Example:

Next example is for default syntax. It looks like C statement. For each case you must use “:” after the value and you need to issue “break” statement. This will force switch statement to terminate. If there is no break the statement continue to evaluate next cases until a break is reach, otherwise default branch is executed.

Alternative syntax:

Alternative syntax is ending the switch statement with keyword “endswitch”. Observe beginning of the block is mark with “:” and not with {…}. This syntax is just redundant, there is no advantage to use it.

Jump: “goto”

It is a legacy statement, not really necessary in your code. It is a good practice to avoid using it. However, sometimes you can make a shorter program using this statement. In next example we show how to exit from two nested loops using goto end:

Output:

(0, 1)(0, 2)(0, 3)
(1, 1)(1, 2)(1, 3)
(2, 1)(2, 2)(2, 3)
(3, 1)(3, 2)(3, 3)
done

Note: You can jump backwards to a prior defined label or forward. But you can not jump from outside of a loop to inside a loop. You can not jump into a function from another function. This makes goto more sage than it use to be in Fortran or Basic.

Exceptions: “try”

An exception is a abnormal situation that can lead to unpredictable results that can cause a program to stop functioning. Normally in such occasions the program will stop immediately and report an error or crash.  

In PHP there is a flow control statement: “try” used to protect a sequence of code against exceptions. In case of an error we can “catch” exceptions and have a chance to analyze the situation. Then we can report an error message and continue or propagate the error.

Example:

Note:  This short program will always fail since $x is 0 and we know division by 0 is not possible. So we “throw” and Exception object with message: “Division by zero!”. 

Output:

Exception: Division by zero!

Note: This subject will be explained in more details in future articles, after you learn about functions, classes and objects. For now just remember one thing:  “try” block is a control flow statement used to patch exceptions.

Next article: Functions