1

I want to output a taxonomy so that if one element is selected it shows (e.g. A) that but if two are selected it shows (e.g. A & B) but if more are selected it adds commas then add & to the last one (e.g A, B & C or A, B, C & D)

This is the code I have so far

$colours = get_the_terms( $post->ID, 'colour' );   
if ( $colours ) {
   $i = 0;
   foreach ( $colours as $colour ) {
       if(1==$i) {
          echo ' & ';
       }
       echo $colour->name;
       $i++;
   } 
} 

This currently does this (e.g. 1 selected = Red then 2 selected = Red and Green) but once more than two are selected it does this (e.g. 3 selected = Red & GreenBlack).

zigzagad
  • 21
  • 3
  • 2
    You add all selected items to an array and then use ``implode('& ', $items)`` for the output. – arkascha Oct 19 '18 at 11:30
  • Possible duplicate of [PHP Add commas to items with AND](https://stackoverflow.com/questions/9065929/php-add-commas-to-items-with-and) – Barry Oct 19 '18 at 11:33

1 Answers1

3

Join all elements using , except last one. Append last element with &:

if (count($colours) > 1) {
    $lastColour = array_pop($colours);
    echo implode(', ', $colours) . ' & ' . $lastColour;
} else {
    echo current($colours);
}

Example

Justinas
  • 41,402
  • 5
  • 66
  • 96