Can not using braces "{ }" in IF in PHP cause problems?

Question:

Generally for checks that modify just one line I've avoided using curly braces, as PHP accepts this method, but I rarely see code from other programmers like that… Examples

my method

if($thumb->SaveInDB('imagens','img'))
    $ok = true;
else
    $ok = false;

Normal method

if($thumb->SaveInDB('imagens','img'))
{
    $ok = true;
}
else
{
    $ok = false;
}

Does it make any difference to use the "{ }" braces in these cases? is there the possibility of php returning an error or something?

Answer:

In fact, the IF without braces can only be used in the execution of a command and when it is a chain of commands you use braces to indicate that, at the moment { until the end } execute. See the examples below.

The same logic applies to languages ​​like PHP, Javascript, Typescript and C#.

This will work!

PHP

if($meuVar == true)
   echo 'verdadeiro';
else
   echo 'falso';

if($meuVar == true)
{
   echo "Sim";
   echo "<br> É verdadeiro";
}
else
   echo "Não <br> É verdadeiro";

This will NOT work!

PHP

if($meuVar == true)
   echo 'Sim';
   echo '<br> é Verdadeiro';
else
   echo 'Não';
   echo '<br> é Verdadeiro';

I use it myself in my code when I will only execute one command, this method also works in other languages ​​such as C#

This is also true for other commands, examples below.

PHP

for($i == 0; $i < 10; $i++)
   echo $i;

while($i < 10)
   echo $i++;

foreach($items as $item)
   echo $item->meuCampo;

I'll leave a for and while demo in action. DEMO

Scroll to Top