MDanz Posted June 24, 2014 Share Posted June 24, 2014 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. Quote Link to comment https://forums.phpfreaks.com/topic/289275-help-with-shorthand-if-statements/ Share on other sites More sharing options...
Solution mac_gyver Posted June 24, 2014 Solution Share Posted June 24, 2014 (edited) 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 }. Edited June 24, 2014 by mac_gyver Quote Link to comment https://forums.phpfreaks.com/topic/289275-help-with-shorthand-if-statements/#findComment-1483156 Share on other sites More sharing options...
Psycho Posted June 24, 2014 Share Posted June 24, 2014 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>"; } Quote Link to comment https://forums.phpfreaks.com/topic/289275-help-with-shorthand-if-statements/#findComment-1483160 Share on other sites More sharing options...
Jacques1 Posted June 24, 2014 Share Posted June 24, 2014 (edited) 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. Edited June 24, 2014 by Jacques1 Quote Link to comment https://forums.phpfreaks.com/topic/289275-help-with-shorthand-if-statements/#findComment-1483162 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.