Is it a bad practice to have too many nested PHP if-statements?
Right now, I have something like this:
<?php if ( ! is_front_page() ) : ?>
<?php if ( $count >= 1 ) : ?>
<?php if ( $count == 1 ) : ?>
<h2 class="dark-title"><?php _e( 'Top Reply (Latest)' ); ?></h2>
<?php else : ?>
<h2 class="dark-title"><?php _e( 'Top Replies (Latest)' ); ?></h开发者_开发问答2>
<?php endif; ?>
<?php endif; ?>
<?php endif; ?>
There are 3 nested if-statements I would like to know if this is a bad practice. If it is, how can I clean this code?
It is if the conditions are very simple and their are no else cases.
Also, opening useless <?php
processing instructions and using the uncommon endif
form instead of braces are definitely not encouraged. Instead, write:
<?php
if (!is_front_page() && ($count >= 1)) {
echo '<h2 class="dark-title">';
echo _e(($count==1) ? 'Top Reply (Latest)' : 'Top Replies (Latest)');
echo '</h2>';
}
?>
...if you need more than 3 levels of indentation, you're screwed... - Linus Torvalds
It's fine what you've done. In general your firstmost care should be whether your code is readable, not how many levels of nesting you use.
It is certainly a bad idea to repeat markup. If you want to change something, add a class for example, you have to do it in two places.
In some cases, when you just want to assign a value based on a condition, you can use the ternary operator (condition ? iftrue : iffalse
), just never nest it.
<?php if ( ! is_front_page() && $count >= 1 ) : ?>
<h2 class="dark-title">
<?php _e( $count == 1 ? 'Top Reply (Latest)' : 'Top Replies (Latest)' ); ?>
</h2>
<?php endif; ?>
It's fairly common. If you want to clean up the code, refactor stuff into separate functions/methods. In your specific case you could also get rid of one nesting by doing if($count == 1) and then elseif($count > 1).
精彩评论