Cleanest Way to Select Every Second Element in a Loop?

What’s the quickest and easiest way to select every second element in the loop?

At the moment I’m using this strange method:

Read More
<ul>
<?php $k = 1; ?>
  <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <li class="<?php if($k%2 == 0) echo 'last'; ?>"><?php the_content(); ?></li>
<?php $k++; ?>
<?php endwhile; ?>
<?php endif; ?>
</ul>

Can’t use nth-child since IE doesn’t support it and CSS3 PIE isn’t playing nice with my site at the moment.

Related posts

Leave a Reply

1 comment

  1. I wouldn’t consider that strange :). WordPress uses a similar method to apply the ‘alternate’ class to every other row in the tables on the admin page, something like:

    <ul>
      <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
         <?php $class = (empty($class) ? 'class="alternate"' : '');?>
         <li <?php echo $class; ?> ><?php the_content(); ?></li>
      <?php endwhile; ?>
      <?php endif; ?>
    </ul>