Output data to multiple elements with one loop

Last modified March 12, 2019
.* :☆゚

The short of it

When you’re iterating over a lot of data for display using PHP, it can get messy pretty quickly especially when markup is in the mix. This can get even more complex if you need the same loop to output data into multiple different wrapping elements.

The technique below is not necessarily a better way of solving this issue (sometimes, using the same loop is actually better for readability), however in the interests of keeping things DRY (do not repeat yourself), I’ll sometimes use this to save me from having to repeat the same loop twice.

 <?php if( have_rows('content_panels') ):
    $titles = '';
    $contents= '';
    <?php while( have_rows('content_panels') ): the_row();
        // vars
        $title = get_sub_field('title');
        $content = get_sub_field('content');

        //format the title
        $urlize_title = sanitize_title($title);
        $formatted_title = '<a href="#' . $urlize_title . '" title="' . $title . '">' . $title . '</a>';

        //format the content
        $formatted_content = '<section id="' . $urlize_title . '" class="panel-content"><h2>' . $title . '</h2>' . $content . '</section>';

        //concatenate the strings for display
        $titles .= $formatted_title;
        $contents .= $formatted_content;
    <?php endwhile; ?>

    <div class="cell panel-links">
        <?php echo $titles; ?>

    <div class="cell panel-content">
        <?php echo $contents; ?>

<?php endif; ?>

The long of it

Read more about how this loop works