Jump to content

Help with shorthand if statements


MDanz

Recommended Posts

I always have trouble reading shorthand statements, as i am used to always using brackets. So when i view someones code and they use shorthand, i get confused.  Can i get a clear explanation on the example below:

if ( have_posts() ) : while ( have_posts() ) : the_post();
					the_content();
					
					endwhile; else: 
					
						echo "<p>Sorry, no posts matched your criteria.</p>";
					
					endif;

I've always been accustomed to using brackets, so i have trouble understanding the above quickly.

Link to comment
https://forums.phpfreaks.com/topic/289275-help-with-shorthand-if-statements/
Share on other sites

those are actually alternative syntax, they are by no means shorthand (they require more typing then the traditional syntax.)

 

simply 'read' any : as an opening { and any endwhile; endif;, ... as a closing } and any else;, elseif(): also counts as it's parent's closing }.

Yeah, that block of code is hard to read. Never liked that alternative syntax. That code could be rewritten as

 

if ( have_posts() )
{
    while ( have_posts() )
    {
        the_post();
        the_content();
    }
}
else
{
    echo "<p>Sorry, no posts matched your criteria.</p>";
}

This syntax is supposed to be used in templates, not in code.

 

PHP used to be a template engine for embedding short sections of code within HTML markup. That's why there are PHP tags, and that's why the alternative syntax exists:

<h1>My blog</h1>
<ul>
    <?php foreach ($blog_posts as $blog_post): ?>
        <li>
            <h2><?= html_escape($blog_post['title']) ?></h2>
            <p><?= html_escape($blog_post['text']) ?></p>
        </li>
    <?php endforeach; ?>
</ul>

You can't really use the usual brace syntax here, because it would be difficult to tell which brace terminates which statement.

 

Now that PHP has become a full-blown programming language, people tend to embed their HTML markup in the code instead of the other way round, and the alternative syntax is rarely used. That's actually a pity, because it would help fighting the spaghetti code problem.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.