Support

Account

Home Forums General Issues Comma separated list with & for last value

Solved

Comma separated list with & for last value

  • Hi,

    I have a select field type in ACF with the ability to select multiple options.. Here’s the code I’m currently using to display a list of all the airports selected, separated with a comma:

    <?php $departure_airport_checked_values = get_field('departure_airport');
     if( count($departure_airport_checked_values)){
    							foreach($departure_airport_checked_values as $k=>$departure_airport_value){
    											if($k) echo ', ';
    												echo $departure_airport_value;
    											}
    }
    ?>

    This code would display like the following:

    Value 1, Value 2, Value 3, Value 4

    What I’m trying to do is replace the last comma with an & symbol, so the list looks like this:

    Value 1, Value 2, Value 3 & Value 4

    Additionally, if only two values are selected, display them like this:

    Value 1 & Value 2

    Any pointers, please?

  • 
    $value = get_field('departure_airport');
    $last_value = '';
    if (count($value) > 1) {
      $last_value = ' & '.array_pop($value);
    }
    echo implode(', ', $value),$last_value;
    
  • Thanks, John, that worked perfectly. Much appreciated!

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.