I know how to loop through items of an array using foreach and append a comma, but it's always a pain having to take off the final comma. Is there an easy PHP way of doing it?
$fruit = array('apple', 'banana', 'pear', 'grape');
Ultimately I want
$result = "apple, banana, pear, grape"
A functional solution would go like this:
This is how I've been doing it:
Output:
Live Demo: http://ideone.com/EWK1XR
EDIT: Per @joseantgv's comment, you should be able to remove
rtrim()
from the above example. I.e:Sometimes you don't even need php for this in certain instances (List items each are in their own generic tag on render for example) You can always add commas to all elements but last-child via css if they are separate elements after being rendered from the script.
I use this a lot in backbone apps actually to trim some arbitrary code fat:
Basically looks at the element, targets all except it's last element, and after each item it adds a comma. Just an alternative way to not have to use script at all if the case applies.
I prefer to use an IF statement in the FOR loop that checks to make sure the current iteration isn't the last value in the array. If not, add a comma
Another way could be like this:
Output of
$result
is a nicely formatted comma-separated list.