ACF put a comma after the last repeater field value

The question:

I’ve the following code

<?php if(have_rows('ore')):?>

        <?php while( have_rows('ore')): the_row();

                $start = get_sub_field('start');
                $end = get_sub_field('end');
        ?>

         <?php if( get_row_index() != 1 ){ echo '/'; }?>
               <?php echo $start;?> – <?php echo $end;?>    
    
    <?php endwhile;?>
<?php endif;?>

Which outputs the two fields (“start” & “end”) in this form: 12.00 – 13.00.
In case there are more than one, they’ll be displayed like this 12.00 – 13.00 / 15.40 – 16.00 and so on.

How can I put a comma after the last field? (–> 12.00 – 13.00 / 15.40 – 16.00, or even 12.00 – 13.00,)
(I guess I’ve to count the number of rows and when reaching the last one, put the comma …)

Thanks

David

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

You’re generating whitespace because of the blank line between the echo $end block and the endwnile, and because you’re switching in and out of PHP which means everything between the ?> and <?php – i.e. all of the whitespace – will get echoed out. (HTML then merges the blank lines and spaces into a single space for display.)

You can just do this a single PHP block to save switching in and out of PHP, which will prevent any extra whitespace getting echoed:

<?php
if (have_rows('ore')) {
    while(have_rows('ore')) {
        the_row();

        $start = get_sub_field('start');
        $end = get_sub_field('end');

        if( get_row_index() != 1 ) {
            echo '/';
        }
        echo esc_html($start).' - '.esc_html($end);
    }
    echo ',';
}
?>

Note that I’ve also added esc_html() around the $start and $end values as you echo them. I might also check if these were present or not too before using them, unless you’re positive they’ll always have values.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment