Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

php - Comma separated list from array with "and" before last element

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.

Currently, I have a nice way of having a comma separated list using this...

$comma_list = implode(', ', $number_list);

However, I'd like to keep with English convention and have the word "and" before the last element. So, let's say $number_list contains the values 4, 5, 6, 7. I would want to echo a statement like, "The list is 4, 5, 6, and 7."

Any ideas how to get that and in there?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...