If I have an array that looks like this:
$str = '';
if( $_POST['first'] )
$str = $_POST['first'];
if( $_POST['second'] )
$str .= ($str != '' ? ',' : '') . $_POST['second'];
if( $_POST['third'] )
$str .= ($str != '' ? ',' : '') . $_POST['third'];
if( $_POST['fourth'] )
$str .= ($str != '' ? ',' : '') . $_POST['second'];
$str .= ($str != '' ? '.' : '');
Which gives me something like this:
Joe, Adam, Mike.
However, I would like to add an “and” before the last item.
So it would then read:
Joe, Adam, and Mike.
How can I modify my code to do this?
Arrays are awesome for this:
You should probably special case the above for when there’s one item. I, in fact, wrote a function called “conjunction” which does the above, and includes the special case:
Nice question!
Updated: General purpose way to do this:
I added correct $_POST checking to avoid notices, and blank values.