Alex Rivera | Logout

Implode an array with ", " and add "and " before the last item

Asked 2011-12-21T07:01:23.380
94

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?

Edit
Report

2 Answers

32

You can pop last item and then join it with the text:

$yourArray = ('a', 'b', 'c');
$lastItem = array_pop($yourArray); // c
$text = implode(', ', $yourArray); // a, b
$text .= ' and '.$lastItem; // a, b and c
answered 2011-12-21T07:05:45.613
0

try this

$arr = Array("coke","sprite","fanta");
$str = "";
$lenArr = sizeof($arr);
for($i=0; $i<$lenArr; $i++)
{
    if($i==0)
        $str .= $arr[$i];
    else if($i==($lenArr-1))
        $str .= " and ".$arr[$i];
    else
        $str .= " , ".$arr[$i];
}
print_r($str);
answered 2011-12-21T07:13:41.010

Your Answer