将逗号添加到项目中,并使用“和" PHP接近尾声 [英] Add commas to items and with "and" near the end in PHP

查看:54
本文介绍了将逗号添加到项目中,并使用“和" PHP接近尾声的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要为除最后一项以外的所有项添加逗号.最后一个必须有和".

I want to add a comma to every item except the last one. The last one must have "and".

第1项,第2项和第3项

Item 1, Item 2 and Item 3

但是项目可以是1 +

But items can be from 1 +

如果有一项:

项目1

如果有两项:

第1项和第2项

Item 1 and Item 2

如果有三个项目:

第1项,第2项和第3项

Item 1, Item 2 and Item 3

如果有四个项目:

第1项,第2项,第3项和第4项

Item 1, Item 2, Item 3 and Item 4

等,等等.

推荐答案

这是一个函数;只需传递数组即可.

Here’s a function for that; just pass the array.

function make_list($items) {
    $count = count($items);

    if ($count === 0) {
        return '';
    }

    if ($count === 1) {
        return $items[0];
    }

    return implode(', ', array_slice($items, 0, -1)) . ' and ' . end($items);
}

演示

这篇关于将逗号添加到项目中,并使用“和" PHP接近尾声的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆