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: {...}.
This statement uses a logical conditional expression to make a decision about execution of next statement. It has two branches: "true" branch and "false" branch. On each branch we can execute one statement or multiple statements encapsulated into a block of code.
decision diagram
Patterns:
if (expr) {
statements;
} // true block;
else {
statements;
} // false block;
Alternative:
if (expr):
statements;
else:
statements;
endif;
<?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:
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.
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:
<?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
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".
<?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.
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.
<?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
?>
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.
while loop diagram
<?php
/* default syntax */
$i = 1;
while ($i <= 10) {
echo $i++, ",";
}
echo "<br>";
/* alternative syntax */
$i = 1;
while ($i <= 10):
echo $i,",";
$i++;
endwhile;
?>
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.
do-while diagram
<?php
$i = 10;
do {
echo $i--,",";
} while ($i > 0);
?>
Note: The alternative syntax does not work for "do..while" statement.
<?php
$i = 10;
/* will fail */
do:
echo $i--,",";
while ($i > 0);
?>
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.
Loop Intreruptions
<?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.
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.
Switch Diagram
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.
<?php
$i = 2;
switch ($i) {
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
case 3:
echo "i equals 3";
break;
case 4:
echo "i equals 4";
break;
default:
echo "i is 0 or > 4";
}
?>
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.
<?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;
?>
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:
<?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.
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.
<?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.
Read next: Functions