(or add comma to all items but the last one...)

Most of the information I have found relates to using a counter within a foreach loop. In this particular situation I am using Advanced Custom Fields and I am within a standard loop, not a foreach loop.

I need to add a comma to the end of each item except the last.

<?php while( has_sub_field('images') ): ?>
    <?php $image = wp_get_attachment_image_src(get_sub_field('image'), 'wsn_canvas'); ?>
    <?php echo $image[0]; ?>
    //echo comma here
<?php endwhile; ?>
  • $output = $image[0] .','; endwhile; $output = substr_replace($output ,"",-1); echo $output; ?? you can also get rid of all your php tags .. you have no HTML in there. – krembo99 Apr 21 '13 at 4:24
up vote 1 down vote accepted

There is nothing 'standard' about a while loop and in this case it makes things harder, since you need a total count of all the items in loop in order to know if you are on the last item or not. It is not obvious how to get that total count with a function like has_sub_field but there is a quick way to do this that I use fairly often to build character separated strings when I don't know how many items will be in the final result.

$attach = array();
while( has_sub_field('images') ):
    $image = wp_get_attachment_image_src(get_sub_field('image'), 'wsn_canvas');
    $attach[] = $image[0];
endwhile;
echo implode(', ',$attach);

Use wp_sprintf_l( $pattern, $args ):

$images = array();

while( has_sub_field('images') )
{
    $image = wp_get_attachment_image_src(get_sub_field('image'), 'wsn_canvas');
    $images[] = $image[0];
}

if ( ! empty ( $images ) )
    echo wp_sprintf_l( '%l', $images );

This will use localized separators, an Arabic comma between the items for Arabic for example.

The separator for the last two items is by default ', and ' (Oxford comma), but you can change that too with a filter:

add_filter( 'wp_sprintf_l', 'replace_oxford_comma' );

function replace_oxford_comma( $separators )
{
    $separators['between_last_two'] = ' and';
    return $separators;
}

It's also possible to create comma separated lists with a terminal 'and' (Oxford style or not) using only CSS: https://stackoverflow.com/questions/6587807/comma-delimited-lists-with-css-i-want-an-oxford-comma

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.