18

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.

elijahcarrel
  • 3,787
  • 4
  • 17
  • 21
  • this works always no matter which version of php you are using. [`read`](http://php.net/manual/en/control-structures.elseif.php) – xkeshav Jul 02 '12 at 05:01

6 Answers6

22

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.

Community
  • 1
  • 1
John C
  • 8,223
  • 2
  • 36
  • 47
7

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";
}
Christoffer
  • 7,470
  • 9
  • 39
  • 55
3

you code is acceptable and will work fine in all version of php and IMHO: not only php all other languages support the same for single statment. but for readability and avoid any error, in case you might need to add multiple statements later, it is recommended to use block statments

Blaster
  • 9,414
  • 1
  • 29
  • 25
Raab
  • 34,778
  • 4
  • 50
  • 65
0

The code is always acceptable. It will consistently work in all versions of PHP.

John K
  • 353
  • 4
  • 18
0

Yes, but it must to be only one row sentences. Id you need to use more rows you will need brackets.

Martin Revert
  • 3,242
  • 2
  • 30
  • 33
0

Please go throught PHP online documentation,

http://www.php.net/manual/en/control-structures.elseif.php.

if($x > $y):
echo 'x is greater';
elseif($a == $b): // Note the combination of the words.
echo 'equal';
else:
echo 'y is greater';
endif;
Anoop Pete
  • 492
  • 2
  • 4
  • 17