Jump to content

Alternative syntax for control structures (a tip for newbies)


kongondo
 Share

Recommended Posts

This is a quick tip for my front-end developer peeps and other wanna-be-coders like me....I have been seeing this "strange" <?php endif; ?> code in some code here in the forums and in some template files.

<?php if ($a == 5): ?>
<p>A is equal to 5</p>
<?php endif; ?>
//In the above example, the HTML block "A is equal to 5" is nested within an if statement written in the alternative syntax. The HTML block would be displayed only if $a is equal to 5.

//The alternative syntax applies to else and elseif as well.

I have largely ignored it until I read about it more and wow! I wish I knew about it earlier. Anyway, you might want to read up about it. In a nutshell, it makes mixing PHP and HTML much more friendly in some cases. It helps avoid echoing out a lot of HTML but instead gives you flexibility to just type them out normally...

A few resources to help you understand the alternative syntax.

http://php.net/manual/en/control-structures.alternative-syntax.php
http://www.brian2000.com/php/understanding-alternative-syntax-for-control-structures-in-php/
http://www.stoimen.com/blog/2010/03/10/php-if-else-endif-statements/
http://www.trans4mind.com/personal_development/phpTutorial/controlStructures.htm
http://stackoverflow.com/questions/564130/difference-between-if-and-if-endif
http://stackoverflow.com/questions/6023418/when-do-i-use-if-endif-versus-if
http://www.trans4mind.com/personal_development/phpTutorial/controlStructures.htm

  • Like 2
Link to comment
Share on other sites

And worth mentioning 

<?php foreach($pages as $page): ?>
  // do something here in mixed html & php
  // probably a few lines of it
<?php endforeach; ?>

It makes code much more readable, but you would expect to use this most in output templates, where there is a lot of html going on.

  • Like 2
Link to comment
Share on other sites

@PWired. Thanks. I am humbled. I try to do my bit. Though, truth of the matter is that I've taken much more than I've given back. There's some great people in this community; I am awed by their generosity.

  • Like 3
Link to comment
Share on other sites

It's also possible to do this:

<?php if ($a == 5) { ?>
<p>A is equal to 5</p>
<?php } ?>
//In the above example, the HTML block "A is equal to 5" is nested within an if statement written in the alternative syntax. The HTML block would be displayed only if $a is equal to 5.

//The alternative syntax applies to else and elseif as well.
  • Like 1
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...