[php] How do I create a comma-separated list from an array in PHP?

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"

This question is related to php arrays

The answer is


$fruit = array('apple', 'banana', 'pear', 'grape');    
$commasaprated = implode(',' , $fruit);

$letters = array("a", "b", "c", "d", "e", "f", "g"); // this array can n no. of values
$result = substr(implode(", ", $letters), 0);
echo $result

output-> a,b,c,d,e,f,g


A functional solution would go like this:

$fruit = array('apple', 'banana', 'pear', 'grape');
$sep = ','; 

array_reduce(
    $fruits,
    function($fruitsStr, $fruit) use ($sep) {
        return (('' == $fruitsStr) ? $fruit : $fruitsStr . $sep . $fruit);
    },
    ''
);

Similar to Lloyd's answer, but works with any size array.

$missing = array();
$missing[] = 'name';
$missing[] = 'zipcode';
$missing[] = 'phone';

if( is_array($missing) && count($missing) > 0 )
        {
            $result = '';
            $total = count($missing) - 1;
            for($i = 0; $i <= $total; $i++)
            { 
              if($i == $total && $total > 0)
                   $result .= "and ";

              $result .= $missing[$i];

              if($i < $total)
                $result .= ", ";
            }

            echo 'You need to provide your '.$result.'.';
            // Echos "You need to provide your name, zipcode, and phone."
        }

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

$fruit = array("apple", "banana", "pear", "grape");

for($i = 0; $i < count($fruit); $i++){
    echo "$fruit[$i]";
    if($i < (count($fruit) -1)){
      echo ", ";
    }
}

If doing quoted answers, you can do

$commaList = '"'.implode( '" , " ', $fruit). '"';

the above assumes that fruit is non-null. If you don't want to make that assumption you can use an if-then-else statement or ternary (?:) operator.


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:

.likers a:not(:last-child):after { content: ","; }

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.


Result with and in the end:

$titleString = array('apple', 'banana', 'pear', 'grape');
$totalTitles = count($titleString);
if ($totalTitles>1) {
    $titleString = implode(', ', array_slice($titleString, 0, $totalTitles-1)) . ' and ' . end($titleString);
} else {
    $titleString = implode(', ', $titleString);
}

echo $titleString; // apple, banana, pear and grape

Follow this one

$teacher_id = '';

        for ($i = 0; $i < count($data['teacher_id']); $i++) {

            $teacher_id .= $data['teacher_id'][$i].',';

        }
        $teacher_id = rtrim($teacher_id, ',');
        echo $teacher_id; exit;

Another way could be like this:

$letters = array("a", "b", "c", "d", "e", "f", "g");

$result = substr(implode(", ", $letters), 0, -3);

Output of $result is a nicely formatted comma-separated list.

a, b, c, d, e, f, g

This is how I've been doing it:

$arr = array(1,2,3,4,5,6,7,8,9);

$string = rtrim(implode(',', $arr), ',');

echo $string;

Output:

1,2,3,4,5,6,7,8,9

Live Demo: http://ideone.com/EWK1XR

EDIT: Per @joseantgv's comment, you should be able to remove rtrim() from the above example. I.e:

$string = implode(',', $arr);