168

Are there any differences between...

if ($value) {

}

...and...

if ($value):

endif;

?

Ambo100
  • 1,185
  • 3
  • 15
  • 28
alex
  • 479,566
  • 201
  • 878
  • 984
  • 1
    The second way has been there since PHP4, if not earlier. – Miles Feb 19 '09 at 06:24
  • see also: http://stackoverflow.com/questions/381259/php-conditionals-brackets-needed/ – Jacco Feb 19 '09 at 11:50
  • 1
    Most answers aren't really addressing [the main point](http://stackoverflow.com/a/5657678/274502): which works better when you're looking at some code and there are lots of closing commands such as `} } } }` (which can be done with `endif` as well) and you want to know where they were open? [The answer is neither](http://stackoverflow.com/a/5657678/274502). It's basically the [first "rule" of python design principles](http://docs.python-guide.org/en/latest/writing/style/). – cregox Dec 15 '14 at 17:19
  • 7
    Obviously `{}` is better and `: endif;` is an atrocity that would not exist if life were fair. With a good text editor you'll have a keyboard shortcut for matching brackets, to jump you from the opening to the closing or vice versa. No such thing does nor ever could exist for the hideous `: endif;` syntax. – developerwjk Feb 04 '15 at 22:09
  • 4
    @developerwjk how could that never exist? – alex Feb 05 '15 at 03:54
  • @developerwjk, its useful... ` test test2 ` – Yousha Aleayoub May 06 '17 at 15:58
  • @Yousha Aleayoub, As long as its limited to one-liners its not so bad I guess. – developerwjk May 08 '17 at 15:58
  • @YoushaAleayoub "useful" seems to imply you couldn't do that with brackets, but you definitely can, and I'd go as far as to say it looks cleaner, too, personally ` test test2 ` – Brian Leishman Jul 14 '18 at 16:15
  • @developerwjk your answer is opinion based, Watch out for the mods! [smiles] –  Jun 10 '22 at 08:53

16 Answers16

189

They are the same but the second one is great if you have MVC in your code and don't want to have a lot of echos in your code. For example, in my .phtml files (Zend Framework) I will write something like this:

<?php if($this->value): ?>
Hello
<?php elseif($this->asd): ?>
Your name is: <?= $this->name ?>
<?php else: ?>
You don't have a name.
<?php endif; ?>
geoff
  • 2,251
  • 1
  • 19
  • 34
Thomaschaaf
  • 17,847
  • 32
  • 94
  • 128
  • @ alex - i think so. however if you google stringtemplate (all one word) you'll find that they use a very similar syntax to solve this same problem. I guess you could argue the code is cleaner looking? Maybe this is common for interpreted templating/languages... – Brian Sweeney Feb 19 '09 at 06:28
  • 39
    @alex It will work with curly brackets as well, but at least personally I find this way kind of clearer in things like this. Cause they you know that it is the end of an if, and not the end of a loop of some sort or something else. Think you have endfor and endwhile or something similar too. – Svish Jun 15 '09 at 07:16
  • 10
    I wouldn't use the = ?> because it is not supported on all servers, especially shared hosting ones that don't allow you to change php.ini. – Siqi Lin Aug 01 '10 at 18:57
  • 1
    I actually prefer to use { } because when I click on the opening { the closing } will be highlighted by the ide – AntonioCS Feb 17 '11 at 14:12
  • 2
    The pertinent point is - you can tell exactly what is ending even with many lines of HTML inbetween the preceding if / else and this statement. – Fenton Feb 23 '11 at 14:21
  • 2
    I dun see using alternative syntax in your example help to reduce number of echoes. – ajreal Feb 23 '12 at 07:17
  • 1
    @Exception Just an update, as of PHP 5.4 = ?> is always available now. http://www.php.net/ChangeLog-5.php#5.4.0 – CLo Mar 28 '12 at 15:34
  • 1
    Yes! curly brackets and ?> do work too, and personally I will always use the curly brackets approach, because I can use the "match brackes" feature of my dev-software, as with the endif approach I can't. In addition: I've never seen shared hosting, on which the curly brackets with ?> or = inside, does not work. It just works everywhere! – PatlaDJ Dec 20 '12 at 09:26
  • 9
    why "the second one is great if you don't want to have a lot of echos in your code"? I think it is same for the traditional syntax `{}` as well. No extra echo is needed ` ... ... `. What is the difference with ` ... ... `? – Sithu Jan 09 '14 at 07:54
  • 10
    Not sure why this answer is the highest, as it's not a great example (you can achieve the exact same with curly braces). – Reinier Kaper Sep 18 '14 at 18:04
  • I think the point here is: it's important to be descriptive. I rather just add a comment as per [my answer there](http://stackoverflow.com/a/5657678/274502). – cregox Dec 15 '14 at 17:09
  • fwiw idt you can mix nested syntaxes. Ie outer conditional can't be brackets if inner uses endif; – hot_barbara Apr 04 '22 at 23:09
29

At our company, the preferred way for handling HTML is:

<? if($condition) { ?>
   HTML content here
<? } else { ?>
   Other HTML content here
<? } ?>

In the end, it really is a matter of choosing one and sticking with it.

alex
  • 479,566
  • 201
  • 878
  • 984
gahooa
  • 131,293
  • 12
  • 98
  • 101
13

They are indeed both the same, functionally.

But if the endif is getting too far from the correspondent if I think it's much better practice to give a referencing comment to it. Just so you can easily find where it was open. No matter what language it is:

if (my_horn_is_red or her_umbrella_is_yellow)
{

    // ...

    // let's pretend this is a lot of code in the middle

    foreach (day in week) {
        sing(a_different_song[day]);
    }

    // ...

} //if my_horn_is_red

That actually applies to any analogous "closing thing"! ;)

Also, in general, editors deal better with curly brackets, in the sense they can point you to where it was open. But even that doesn't make the descriptive comments any less valid.

cregox
  • 17,674
  • 15
  • 85
  • 116
  • 1
    agree this is much better - instead of typing out endif - you can say what the if condition is actually doing. – cartalot May 03 '16 at 02:48
  • 1
    @cartalot perhaps that would be even nice to have built in the language (as an optional closing named-block argument), so we could have errors for closing wrong blocks in wrong places! :) – cregox Mar 30 '17 at 09:39
11

I think that it's particularly clearer when you're using a mix of ifs, fors and foreaches in view scripts:

<?php if ( $this->hasIterable ): ?>
    <h2>Iterable</h2>
    <ul>
    <?php foreach ( $this->iterable as $key => $val ):?>
        <?php for ( $i = 0; $i <= $val; $i++ ): ?>
        <li><?php echo $key ?></li>
        <?php endfor; ?>
    <?php endforeach; ?>
    </ul>
<?php elseif ( $this->hasScalar ): ?>
    <h2>Scalar</h2>
    <?php for ( $i = 0; $i <= $this->scalar; $i++ ): ?>
    <p>Foo = Bar</p>
    <?php endfor; ?>
<?php else: ?>
    <h2>Other</h2>
    <?php if ( $this->otherVal === true ): ?>
    <p>Spam</p>
    <?php else: ?>  
    <p>Eggs</p>  
    <?php endif; ?>
<?php endif; ?>

as opposed to:

<?php if ( $this->hasIterable ){ ?>
    <h2>Iterable</h2>
    <ul>
    <?php foreach ( $this->iterable as $key => $val ){?>
        <?php for ( $i = 0; $i <= $val; $i++ ){ ?>
        <li><?php echo $key ?></li>
        <?php } ?>
    <?php } ?>
    </ul>
<?php } elseif ( $this->hasScalar ){ ?>
    <h2>Scalar</h2>
    <?php for ( $i = 0; $i <= $this->scalar; $i++ ){ ?>
    <p>Foo = Bar</p>
    <?php } ?>
<?php } else { ?>
    <h2>Other</h2>
    <?php if ( $this->otherVal === true ){ ?>
    <p>Spam</p>
    <?php } else { ?>  
    <p>Eggs</p>  
    <?php } ?>
<?php } ?>

This is especially useful for long control statements where you might not be able to see the top declaration from the bottom brace.

Harry Mustoe-Playfair
  • 1,369
  • 16
  • 29
11

Here's where you can find it in the official documentation: PHP: Alternative syntax for control structures

Paige Ruten
  • 172,675
  • 36
  • 177
  • 197
7

I think that it really depends on your personal coding style. If you're used to C++, Javascript, etc., you might feel more comfortable using the {} syntax. If you're used to Visual Basic, you might want to use the if : endif; syntax.

I'm not sure one can definitively say one is easier to read than the other - it's personal preference. I usually do something like this:

<?php
if ($foo) { ?>
   <p>Foo!</p><?php
} else { ?>
   <p>Bar!</p><?php
}  // if-else ($foo) ?>

Whether that's easier to read than:

<?php
if ($foo): ?>
   <p>Foo!</p><?php
else: ?>
   <p>Bar!</p><?php
endif; ?>

is a matter of opinion. I can see why some would feel the 2nd way is easier - but only if you haven't been programming in Javascript and C++ all your life. :)

livefree75
  • 720
  • 8
  • 18
  • 1
    No, the brackets are objectively easier to read (when not using the Egyptian version). Even if you're doing the brackets such that they walk like an Egyptian, its easier to read than VB syntax because modern text editors will have a bracket matching function to take you from opening to closing bracket or the other way around. There's no way they could have a VB syntax matching function. Also you have nesting to consider, and VB fails miserably on that. – developerwjk Feb 04 '15 at 22:39
  • @developerwjk don't you agree it is based on somebody's preference? For example like most people say Python is easier to learn than PHP but some PHP maniacs (like me) would find PHP comparatively easier. Don't you agree? –  Jun 10 '22 at 09:22
5

I would use the first option if at all possible, regardless of the new option. The syntax is standard and everyone knows it. It's also backwards compatible.

Paulo
  • 4,275
  • 2
  • 20
  • 20
5

Both are the same.

But: If you want to use PHP as your templating language in your view files(the V of MVC) you can use this alternate syntax to distinguish between php code written to implement business-logic (Controller and Model parts of MVC) and gui-logic. Of course it is not mandatory and you can use what ever syntax you like.

ZF uses that approach.

Itay Moav -Malimovka
  • 52,579
  • 61
  • 190
  • 278
5

There is no technical difference between the two syntaxes. The alternative syntax is not new; it was supported at least as far back as PHP 4, and perhaps even earlier.

You might prefer the alternative form because it explicitly states which control structure is ending: endwhile, for example, can only terminate a while block, whereas if you encounter a brace, it could be closing anything.

You might prefer the traditional syntax, though, if you use an editor that has special support for braces in other C-like syntaxes. Vim, for example, supports several keystrokes for navigating to matching braces and to the starts and ends of brace-delimited blocks. The alternative syntax would break that editor feature.

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
3

In the end you just don't want to be looking for the following line and then having to guess where it started:

<?php } ?>

Technically and functionally they are the same.

Bondt
  • 798
  • 9
  • 22
  • 1
    A good text editor will have a bracket matching shortcut to take you to where it started. Its `endif;` that will be hard to find the start for, because they won't have a similar function for that, and VB-style code does not nest well. – developerwjk Feb 04 '15 at 22:42
3

It all depends, personally I prefer the traditional syntax with echos and plenty of indentations, since it's just so much easier to read.

<?php
    if($something){
        doThis();
    }else{
        echo '<h1>Title</h1>
            <p>This is a paragraph</p>
            <p>and another paragraph</p>';
    }
?>

I agree alt syntax is cleaner with the different end clauses, but I really have a hard time dealing with them without help from text-editor highlighting, and I'm just not used to seeing "condensed" code like this:

<?php if( $this->isEnabledViewSwitcher() ): ?>
<p class="view-mode">
    <?php $_modes = $this->getModes(); ?>
    <?php if($_modes && count($_modes)>1): ?>
    <label><?php echo $this->__('View as') ?>:</label>
    <?php foreach ($this->getModes() as $_code=>$_label): ?>
        <?php if($this->isModeActive($_code)): ?>
            <strong title="<?php echo $_label ?>" class="<?php echo strtolower($_code); ?>"><?php echo $_label ?></strong>&nbsp;
        <?php else: ?>
            <a href="<?php echo $this->getModeUrl($_code) ?>" title="<?php echo $_label ?>" class="<?php echo strtolower($_code); ?>"><?php echo $_label ?></a>&nbsp;
        <?php endif; ?>
    <?php endforeach; ?>
    <?php endif; ?>
</p>
<?php endif; ?>
Yi Yang
  • 31
  • 2
2

I used to use the curly braces but now a days I prefer to use this short-hand alternative syntax because of code readability and accessibility.

2

Personally I prefer making it in two seperate sections but within the same PHP like:

<?php 
    if (question1) { $variable_1 = somehtml; }
    else { $variable_1 = someotherhtml; } 

    if (question2) {
        $variable_2 = somehtml2;
    }

    else { 
        $variable_2 = someotherhtml2;
    }         

etc.
$output=<<<HERE
htmlhtmlhtml$variable1htmlhtmlhtml$varianble2htmletcetcetc
HERE;
echo $output;

?>

But maybe it is slower?

Martin54
  • 1,349
  • 2
  • 13
  • 34
henrik
  • 21
  • 1
1

I used to use curly brackets for "if, else" conditions. However, I found "if(xxx): endif;" is more semantic if the code is heavily wrapped and easier to read in any editors.

Of course, lots editors are capable of recognise and highlight chunks of code when curly brackets are selected. Some also do well on "if(xxx): endif" pair (eg, NetBeans)

Personally, I would recommend "if(xxx): endif", but for small condition check (eg, only one line of code), there are not much differences.

Aaron Chen
  • 130
  • 1
  • 2
  • 8
1

I feel that none of the preexisting answers fully identify the answer here, so I'm going to articulate my own perspective. Functionally, the two methods are the same. If the programer is familiar with other languages following C syntax, then they will likely feel more comfortable with the braces, or else if php is the first language that they're learning, they will feel more comfortable with the if endif syntax, since it seems closer to regular language.

If you're a really serious programmer and need to get things done fast, then I do believe that the curly brace syntax is superior because it saves time typing

if(/*condition*/){
    /*body*/ 
}

compared to

if(/*condition*/):
    /*body*/
endif;

This is especially true with other loops, say, a foreach where you would end up typing an extra 10 chars. With braces, you just need to type two characters, but for the keyword based syntax you have to type a whole extra keyword for every loop and conditional statement.

Andrew
  • 1,322
  • 14
  • 20
1

I think it's a matter of preference. I personally use:

if($something){
       $execute_something;
}
Draemon
  • 33,955
  • 16
  • 77
  • 104
Sergio Rodriguez
  • 8,258
  • 3
  • 18
  • 25
  • 1
    if you'd read the whole thread: alternative syntax is preffered and much cleaner when templating or using foreign language in php views – Juraj Blahunka Jan 20 '10 at 20:38