views:

50

answers:

3

So, why does this work:

<?php if (condition): ?>
    <!--html code here-->
<?php endif; ?>

But not simply this:

<?php
if (condition) { ?>
    <!--html code here-->
    <?
}

I figured it was just style preference, but I actually can't seem to get it to work the second way. Am I just doing something completely wrong? I can't see the purpose of outputting HTML right in the middle of an if statement if you wanted it to always print.

+4  A: 

You need to allow short tag in your php.ini to make <? work

else you have to write <?php } ?>

Michael B.
+1 Eagle Eyes, and short tags are bad.
Jason McCreary
+1 - remember folks, enabling short tags might blow up any XML files you are creating in PHP, i.e. MyXml.php, which starts <?xml ...
Sohnee
@sohnee: That's easy to get around. `$xml = '<' . '?xml'`, if for some reason you can't/won't avoid short tags.
Marc B
A: 

The second way should work like you described considering you have the closing php tags and < ?php

Pete Herbert Penito
You don't need the closing tags (they are implicit). And you can use '<?' instead of '<?php' if you have short tags enabled.
quantumSoup
Firstly, in the question the second example does not have a closing tag when the first one does. So you do need it if you are continuing with HTML. Secondly by default short tags are not set, such a question would indicate that defaults are set.
Pete Herbert Penito
A: 

It does, if you have the right re-opening tag...

<?php
if (condition) { ?>
    <!-- html code -->
<?php
}
Fosco