Comma separated list from array with “and” before last element

后端 未结 6 1254
青春惊慌失措
青春惊慌失措 2020-12-11 05:43

I have an array ($number_list) that has a dynamically generated list of values. There will be at least 1 value in the array and no more than 4.

Currentl

6条回答
  •  眼角桃花
    2020-12-11 05:56

    Remove the last element from the list, implode what's left with commas and then concatenate "and last_element":

    $last = array_pop($number_list);
    $output = implode(', ', $number_list);
    if ($output) {
        $output .= ', and ';
    }
    $output .= $last;
    

    If you prefer, you can also write the above more tersely as

    $last = array_pop($number_list);
    $output = $number_list
        ? implode(', ', $number_list).', and '.$last
        : $last;
    

    Update:

    I have to admit I initially misread the question and thought that it was about replacing the last comma with "and", not adding an "and" before the final item. I have since edited the answer to target the latter scenario. Note that the code can be easily adapted to do either by selecting " and " or ", and " for the "glue" string respectively.

提交回复
热议问题