3.4. Compound expressions. Braces.

Braces allow you to combine several expressions into a group, which is usually called a compound expression (Listing 3.7).

Listing 3.7. Compound expression. Curly.php file

<?php
{
    echo 5 + 5;
    echo 5 - 2;
    echo "Hello, world!";
}

As you can see from the example above, the expressions inside the curly braces are indented. This indent is not required, but it increases the readability of the program. The PSR-2 coding standard requires 4 spaces to indent. If you are used to using the tab character, you should configure your editor to replace the tab character with spaces.

In itself, a compound expression is almost never used; its main purpose is to work together with conditional operators, cycle operators, etc., which we will consider in subsequent chapters.

A compound expression can be located in several PHP inserts. Listing 3.8 shows an example of two compound expressions that are broken up into several PHP inserts. The task of the script is reduced to a random conclusion in the browser window of either the green word “Truth” or the red word “False”. Without the use of curly braces, the if statement would only extend its action to one expression, the use of a compound expression allows its action to be extended to several simple expressions.

COMMENT
The conditional if statement is discussed in Chapter 8.

Listing 3.8. Composite expression in several PHP inserts. Fews.php file

<?php
    if(mt _rand(0, 1)) {
    ?>
    <div style="color: green"><?= "True"; ?></div>
    <?php
} else {
    ?>
    <div style="colo r:red"><?= "False" ?></div>
<?php
}

As you can see in Listing 3.8, a compound expression can be interrupted by tags <?php and ?> at any time and then continued. However, there are exceptions, for example, a compound expression used to form a class cannot be divided by tags <?php and ?>.