Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I use if/endif versus If{}?

Well the question is self explanatory.

In PHP when do I use the if/endif notation instead of the standard if(something){} notation?

Example:

<?php if($a == 5): ?>
A is equal to 5
<?php endif; ?>

Versus:

<?php if($a == 5){ ?>
A is equal to 5
<?php } ?>
like image 457
Naftali Avatar asked May 16 '11 21:05

Naftali


1 Answers

Others have given the answer "for templating", but haven't really explained why. Curly braces are great for denoting blocks, but they kind of rely on indentation to be read clearly. So this is fairly clear:

<?php
if (1 == 2)
{
    while (1 < 2)
    {
        doSomething();
    }
}

It's obvious which brace matches which.

If, however, you're going into an HTML block, you're probably going to stop indenting cleanly. For instance:

<?php
if (1 != 2) { ?>
<div>This always happens! <?php while (true) { ?>
  <p>This is going to cause an infinite loop!</p>
<?php }
}

That's hard to follow. If you use the endif style, it looks a little cleaner:

<?php
if (1 != 2): ?>
<div>This always happens! <?php while (true): ?>
  <p>This is going to cause an infinite loop!</p>
<?php endwhile;
endif;

The content of the code shows more clearly what's being done. For this limited case, it's more legible.

like image 96
lonesomeday Avatar answered Oct 14 '22 18:10

lonesomeday