Zend PHP 7 Certification – Basics – Control Structures

This post covers the Variables section of the PHP Basics chapter when studying for the Zend PHP 7 Certification.

Control structures are a fundamental feature in programming. They allow a script to react differently depending on what has already occurred or based on user input.

We can break down control structures into two different sections: conditional and loop control structures.

Conditional

Use an if construct to allow for conditional execution of code fragments. If the expression below evaluates to TRUE, PHP will execute the echo statement, and if it evaluates to FALSE, it’ll ignore it.

<?php
if ($a > $b)
    echo "a is bigger than b";

else extends an if statement to execute a statement in case the expression in the if statement evaluates to FALSE.

<?php
if ($a > $b) {
    echo "a is bigger than b";
} else {
    echo "a is not bigger than b";
}

Like else, elseif extends an if statement to execute a different statement in case the original if expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE.

<?php
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";
}

Note that sometimes elseif is written as else if.

elseif and else if will only be considered exactly the same when using curly brackets as in the above example.

When using a colon, or alternative syntax as it’s known, to define your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error.

Ternary Operator allows for the simplification of conditional statements.

<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
    $action = 'default';
} else {
    $action = $_POST['action'];
}

For the line (expr1) ? (expr2) : (expr3), expr1 evaluates to expr2 if expr1 evaluates to TRUE, or expr3 if expr1 evaluates to FALSE.

Note that while ternary operators are often used to simplify conditional statements, they can become difficult to read if catering for multiple conditional statements. Bear this in mind when writing your code.

Use the spaceship operator, <=>, for the line (expr) <=> (expr), which returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater.

The switch statement is similar to a series of if statements on the same expression.

An if statement might look like the below.

<?php
if ($i == 0) {
    echo "i equals 0";
} elseif ($i == 1) {
    echo "i equals 1";
} elseif ($i == 2) {
    echo "i equals 2";
}

This can be written as a switch statement.

switch ($i) {
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
}

Only when a case statement is found where the expression evaluates to a value that matches the value of the switch expression does PHP begin to execute the statements.

Please note that if a break statement is not written at the end of a case’s statement list, PHP will go on executing the statements line by line.

For example, if $i evaluated to 0, and none of the case statements contained a break, all three statements would be executed.

A special case statement is the default case. This case matches anything that wasn’t matched by the other cases. For example.

<?php
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";
}

Loops

A while loop tells PHP to execute the nested statement(s) repeatedly as long as the while expression evaluates to TRUE.

The value of the expression is checked each time at the beginning of the loop, and so if the expression evaluates to FALSE, the nested statements will no be run at all.

<?php
$i = 1;
while ($i <= 10) {
    echo $i++;  /* the printed value would be
                   $i before the increment
                   (post-increment) */
}

do-while loops are very similar to while loops, except the expression is checked at the end of each iteration instead of in the beginning.

<?php
$i = 0;
do {
    echo $i;
} while ($i > 0);

The above loop would run one time exactly.

for loops contains three expressions.

for (expr1; expr2; expr3)
    statement
  • The first expression is evaluated (executed) once unconditionally at the beginning of the loop.
  • The second expression is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed
  • The third expression is evaluated (executed) at the end of each iteration
for ($i = 1; $i <= 10; $i++) {
    echo $i;
}

foreach works only on arrays and objects.

foreach (array_expression as $value)
    statement

foreach (array_expression as $key => $value)
    statement

In PHP 7, foreach does not use the internal array pointer.

continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

<?php
while (list($key, $value) = each($arr)) {
    if (!($key % 2)) { // skip even members
        continue;
    }
    do_something_odd($value);
}

As seen earlier in the switch statement, break ends execution of the current structure. It will also end the execution of for, foreach, while and do-while structures.

break also accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. The default value is 1.

<?php
$i = 0;
while (++$i) {
    switch ($i) {
    case 5:
        echo "At 5<br />\n";
        break 1;  /* Exit only the switch. */
    case 10:
        echo "At 10; quitting<br />\n";
        break 2;  /* Exit the switch and the while. */
    default:
        break;
    }
}

View the other sections:

Note: This article is based on PHP version 7.0.