I'm trying to create a string from the elements of an array. Here is my array:
$arr = array ( 1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four' );
Now I want this output:
one, two, three and four
As you see in the output above, default seperator is ,
and last seperator is and
.
Well, there is two PHP functions for doing that, join() and implode(). But none of them isn't able to accept different separator for last one. How can I do that?
Note: I can do that like this:
$comma_separated = implode(", ", $arr);
preg_replace('/\,([^,]+)$/', ' and $1', $comma_separated);
Online Demo
Now I want to know is there any solution without regex?