Remove comma from last item output from loop

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);

Leave a Comment