⊗ppPmCdBOP 93 of 447 menu

The Problem of Optional Curly Braces in Conditions in PHP

Despite the fact that PHP allows the abbreviations shown above without curly braces, I generally do not recommend doing so, as it is a breeding ground for hard-to-catch errors.

Suppose, for example, there is the following code:

<?php $test = 3; if ($test > 0) echo $test; ?>

Now suppose we decided that if the condition is met, we also want to do a second echo:

<?php $test = 3; if ($test > 0) echo $test; echo '+++'; ?>

However, without curly braces, only the first echo is inside the condition, meaning the first echo will execute if the condition is true, and the second one will always execute.

In fact, our code is equivalent to this:

<?php $test = 3; if ($test > 0) { echo $test; } echo '+++'; // this line ended up outside the condition ?>

But we intended this code:

<?php $test = 3; if ($test > 0) { echo $test; echo '+++'; // this line is inside the condition } ?>

This is exactly why it is recommended to always use curly braces, to avoid falling into this kind of errors.

Without running the code, determine what will be displayed on the screen:

<?php $num = 5; if ($num === 5) echo $num; echo '+++'; ?>

Without running the code, determine what will be displayed on the screen:

<?php $num = 0; if ($num === 5) echo $num; echo '+++'; ?>

Without running the code, determine what will be displayed on the screen:

<?php $num = 0; if ($num === 5) echo $num; echo '---'; echo '+++'; ?>
byenru