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

PhpArrays

Php Problem Overview


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"

Php Solutions


Solution 1 - Php

You want to use implode for this.

ie: $commaList = implode(', ', $fruit);


There is a way to append commas without having a trailing one. You'd want to do this if you have to do some other manipulation at the same time. For example, maybe you want to quote each fruit and then separate them all by commas:

$prefix = $fruitList = '';
foreach ($fruits as $fruit)
{
    $fruitList .= $prefix . '"' . $fruit . '"';
    $prefix = ', ';
}

Also, if you just do it the "normal" way of appending a comma after each item (like it sounds you were doing before), and you need to trim the last one off, just do $list = rtrim($list, ', '). I see a lot of people unnecessarily mucking around with substr in this situation.

Solution 2 - Php

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);

Solution 3 - Php

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

Solution 4 - Php

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."
        }

Solution 5 - Php

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

Solution 6 - Php

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 ", ";
    }
}

Solution 7 - Php

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.

Solution 8 - Php

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);
    },
    ''
);


         

Solution 9 - Php

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;

Solution 10 - Php

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.

Solution 11 - Php

$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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionst4ck0v3rfl0wView Question on Stackoverflow
Solution 1 - PhpryeguyView Answer on Stackoverflow
Solution 2 - PhpNateView Answer on Stackoverflow
Solution 3 - PhpWaqar AlamgirView Answer on Stackoverflow
Solution 4 - PhpceasetodreamView Answer on Stackoverflow
Solution 5 - PhpVijay PrajapatiView Answer on Stackoverflow
Solution 6 - PhpLloyd BanksView Answer on Stackoverflow
Solution 7 - PhpLux.CapacitorView Answer on Stackoverflow
Solution 8 - PhpDanielsideView Answer on Stackoverflow
Solution 9 - PhpAriful IslamView Answer on Stackoverflow
Solution 10 - PhpvogomatixView Answer on Stackoverflow
Solution 11 - PhpSanjay AroraView Answer on Stackoverflow