I have an array of items:
array(
'apples',
'oranges',
'pineapples'
)
that I would like to format like so: “Some of my favorite fruits are apples, oranges and pineapples“
So, using PHP I would like to be able to transform that array into a reader friendly apples, oranges and pineapples.
At first I thought I might be able to use array_map but i’m not sure how I would go about telling what the last and 2nd to last items are (it’s easy to add a , after each item with array_map, however you wouldn’t want a comma before the last item)
Thoughts?
Divide the problem to conquer it: Take out the last element, create the comma separated list and then add the last element.
Naturally this only makes sense when there are at least two values in the array. Functions used:
implodeDocs (probably more suitable thanarray_mapin this case) andarray_popDocs.On the other hand, if the values do not contain any
,you can first create a comma separated string with theimplodefunction and then use a regular expression to replace the last comma withand.That done will also work on arrays that have less than 2 elements. I do this in a loop that removes one element from the array in each step so that it shows how it behaves:
Output: