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.
1 2 3 4 | if (expr) statement; else statement; |
Notes:
- Condition is enclosed in round parenthesis (…)
- The second branch is optional.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php //given two variables $a = 1; $b = 2; //check "greater then" relation if ($b > $a) { echo "$b is bigger than $a"; $b = $a; // alter b } echo "<br>"; //new line //check "equal" relation if ($b == $a) echo "$b is equal to $a"; else echo "unexpected"; ?> |
output:
1 2 | 2 is bigger than 1 1 is equal to 1 |
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:
1 2 3 4 5 6 7 8 9 10 11 | <?php $a = 4; $b = 8; if ($a > $b) { echo "a is bigger than b"; } elseif ($a == $b) { echo "a is equal to b"; } else { echo "a is smaller than b"; } ?> |
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”.
1 2 3 4 5 6 7 8 9 10 11 | <?php $a = 4; $b = 8; if ($a > $b): echo "a is bigger than b"; elseif ($a == $b): echo "a is equal to b"; else: echo "a is smaller than b"; 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:
1 2 3 4 5 6 7 8 9 10 | <?php $v = 1; $r = (1 == $v) ? 'Yes' : 'No'; // $r is set to 'Yes' echo $r; // expected: Yes echo "<br>"; //new line $r = (3 == $v) ? 'Yes' : 'No'; // $r is set to 'No' echo $r; // expected: No ?> |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php /* default syntax */ $i = 1; while ($i <= 10) { echo $i++, ","; } echo "<br>"; /* alternative syntax */ $i = 1; while ($i <= 10): echo $i,","; $i++; endwhile; ?> |
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:
1 2 3 4 5 6 7 8 | <?php $i = 10; do { echo $i--,","; } while ($i > 0); ?> |
Note: The alternative syntax does not work for “do..while” statement.
1 2 3 4 5 6 7 | <?php $i = 10; /* will fail */ do: echo $i--,","; while ($i > 0); ?> |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php // default syntax, C like: */ for ($i = 1; $i <= 10; $i++) { echo $i," "; } // end of line, prepare for next echo "<br>"; // alternative syntax with break: for ($i = 1;; $i++): if ($i > 10) { break; } echo $i," "; endfor; ?> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php $i = 2; switch ($i) { case 0: echo "i equals 0"; break; case 1: echo "i equals 1"; break; case 2: echo "i equals 2"; break; default: echo "i is not equal to 0, 1 or 2"; } ?> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php $i = 3; switch ($i): case 0: echo "i equals 0"; break; case 1: echo "i equals 1"; break; case 2: echo "i equals 2"; break; default: echo "i is not equal to 0, 1 or 2"; endswitch; ?> |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php /* Write your PHP code here */ $i = 0; do { $j = 0; do { $j++; echo "($i, $j)"; if (($i == 3) and ($j == 3)): goto end; //jump to end: endif; } while ($j < 3); echo "<br>"; $i++; } while(true); //infinite loop end: echo "<br>","done"; //label ?> |
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:
1 2 3 4 5 6 7 8 9 10 11 | <?php $x = 0; // try { if (!$x) { throw new Exception('Division by zero!'); } echo 1/$x; } catch (Exception $e) { echo 'Exception: ', $e->getMessage(), "<br>"; } ?> |
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