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 } ?>
Short answer:
Always use
if($something) { }
and pretty much never useif/endif
. It's standard since PHP 4.0.0 and while the old syntax is not going away this is the one everybody expects.If you are really looking for a case where you can use if/endif then it's when using php as a template language.
Some people like something like this:
better than
and imho it is because every line "speaks" and that can be helpful when there is a lot of html inbetween the php tags.
I mostly use if/endif when stopping and starting the php code block in between, so nearly always when raw html is being outputted.
For example:
This looks, at least in my opinion, better than the following:
Both methods are acceptable. Some people maintain that the alternative syntax (endif) is more legible in templates. IMHO, with a modern syntax coloring/highlighting error, that no longer holds true. Just pick a style and stick with it.
You can use both, but preffered style and currently known style is the standard
if(expr)
.It is a stylistic choice. They are analogous and one is not better than another.
The former can be good in certain circumstances because it may be easier to read when mired in the middle of an HTML block set.
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:
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:
That's hard to follow. If you use the
endif
style, it looks a little cleaner:The content of the code shows more clearly what's being done. For this limited case, it's more legible.