This array holds a list of items, and I want to turn it into a string, but I don't know how to make the last item have a &/and before it instead of a comma.
1 => coke 2=> sprite 3=> fanta
should become
coke, sprite and fanta
This is the regular implode function:
$listString = implode(', ', $listArrau);
What's an easy way to do it?
I'm not sure that a one liner is the most elegant solution to this problem.
I wrote this a while ago and drop it in as required:
You don't have to use "and" as your join string, it's efficient and works with anything from 0 to an unlimited number of items:
This is quite old at this point, but I figured it can't hurt to add my solution to the pile. It's a bit more code than other solutions, but I'm okay with that.
I wanted something with a bit of flexibility, so I created a utility method that allows for setting what the final separator should be (so you could use an ampersand, for instance) and whether or not to use an Oxford comma. It also properly handles lists with 0, 1, and 2 items (something quite a few of the answers here do not do)
Try this,
OK, so this is getting pretty old, but I have to say I reckon most of the answers are very inefficient with multiple implodes or array merges and stuff like that, all far more complex than necessary IMO.
Why not just:
My go-to, similar to Enrique's answer, but optionally handles the oxford comma.
Another, although slightly more verbose, solution I came up with. In my situation, I wanted to make the words in the array plural, so this will add an "s" to the end of each item (unless the word already ends in 's':
outputs: