Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP If / Else Statements Without Brackets

Tags:

php

Is the following always acceptable code? It seems to work, but does it consistently work with all versions of PHP?

if ($x > $y)
    echo 'x is greater';
elseif ($x == $y)
    echo 'equal';
else
    echo 'y is greater';

Thanks.

like image 302
elijahcarrel Avatar asked Jul 02 '12 04:07

elijahcarrel


People also ask

Do if else statements need brackets?

If the true or false clause of an if statement has only one statement, you do not need to use braces (also called "curly brackets"). This braceless style is dangerous, and most style guides recommend always using them.

Can we use if without curly braces?

Without curly braces only first statement consider in scope so statement after if condition will get executed even if there is no curly braces. But it is Highly Recommended to use curly braces. Because if the user (or someone else) ever expands the statement it will be required.


2 Answers

That is acceptable across version and will work for as long as you want to do only one thing within each control block. Using brackets does help to make it easier to track where blocks start and end, as well as future proofing for when you need to add just one more statement.

This post has a good summary of the various options for if/else blocks in PHP.

like image 110
John C Avatar answered Sep 21 '22 06:09

John C


That works fine, and it's a common way of doing fast if's in many languages. As stated before - if you use more than one line of code you need to put it in a block with bracket.

For example here:

if (x == 1)
 echo "x is one";
 echo "one is x";

The result will be that "x is one" will be echoed if x == 1 while "one is x" will be echoed every time - no matter if x==1 or not.

To get both lines of code to execute only when the condition is true you need to enclose it in a block.

if (x == 1)
{
 echo "x is one";
 echo "one is x";
}
like image 36
Christoffer Avatar answered Sep 21 '22 06:09

Christoffer