How to Split loop in multiple column in archive page

This was a lot more difficult than I anticipated. It seems having multiple while loops can confuse WordPress if it exhausts all the posts. In particular, if a while loop gets to the end of the posts, the next while loop starts from the beginning, causing duplicates to be shown.

To get round this we can use a (not very elegant) do_not_duplicate array to keep track of posts we have already displayed.

Here is my following solution. I’ve used a trick I’ve seen (using foreach) to make it flexible for creating more columns / altering the number of posts in each column. I hope the comments explain everything…

        <?php if ( have_posts() ) : ?>
            <?php
                //Can have as many loops as we like - set how many to appear in each loop.
               //In this example, 4 columns of length 1, 1, 4 and 5 posts respectively.
                $post_counts = array(1, 1,4, 5);
                foreach ($post_counts as $iteration => $max_count) {
                    $count = $max_count;  
                    /* Give our column specific id/class for styling */?>
                    <div id="column-<?php echo $iteration+1; ?> ">
                    //Loop inside the column
                    <?php while ( have_posts() and $count-- ) :
                            the_post(); 
                        /* Check if post has already been shown */
                        if (in_array($post->ID, $do_not_duplicate)) continue;
                            /* If not, add it to our do_not_duplicate array and show it */
                            $do_not_duplicate[] = $post->ID; ?>
                             <a href="https://wordpress.stackexchange.com/questions/31855/<?php the_permalink() ?>" title="" ><?php the_title(); ?></a> </br>
                    <?php endwhile; ?>
                    </div>
            <?php }?>
        <?php else : ?>
            <p>No posts</p>
        <?php endif; ?>

This does the job, but there must be a neater way…?

error code: 523