-1

Possible Duplicate:
Implode array with “, ” and add “and ” before last item

In Wordpress, I am using PHP implode to separate a series of strings with commas, that are stored in an array like so:

Wordpress Loop Iterates through this:

<?php unset($credits); ?>
<?php if(get_field('song_credits')):
    while(has_sub_field('song_credits')): 
       $credits[] = get_sub_field('artist_name');
    endwhile; ?>
    <p><?php echo implode(', ', $credits); ?>.</p>
<?php endif; ?>

Basically, a series of strings is stored into the $credits array, and then I use implode to separate each string with a comma.

I need to add an ampersand right before the last word instead of a comma. Is this possible here?

Community
  • 1
  • 1
JCHASE11
  • 3,901
  • 19
  • 69
  • 132

2 Answers2

1

implode cannot do this directly, but it's not that difficult:

switch (count($credits)) {
    case 0:
        $result = '';
        break;
    case 1:
        $result = reset($credits);
        break;
    default:
        $last = array_pop($credits); // warning: this modifies the array!
        $result = implode(', ', $credits).' & '.$last;
        break;
}
Jon
  • 428,835
  • 81
  • 738
  • 806
0

Taken from: Implode array with ", " and add "and " before last item

<p><?php echo join(' and ', array_filter(array_merge(array(join(', ', array_slice($credits, 0, -1))), array_slice($credits, -1)))); ?></p>

this works just great

Community
  • 1
  • 1
JCHASE11
  • 3,901
  • 19
  • 69
  • 132