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

11

128

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"
Equites answered 12/3, 2010 at 19:23 Comment(0)
N
248

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.

Norford answered 12/3, 2010 at 19:24 Comment(3)
It would make more sense (if trying to add quotes) to call <code>$fruitlist = '"' . implode( '", "', $fruit) . '"';</code>Cortes
The foreach loop is better if you want to manipulate that data in the array before making it into a string; For example, addslashes, or mysql_real_escape_string.Spurtle
Edge case: a string that contains both single and double-quotes - how to adjust for that?Sublieutenant
H
40

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);
Hebrides answered 11/1, 2014 at 18:9 Comment(2)
As answered above, you could just do implode(',', $arr)Among
@Among You're right, I don't know why I use rtrim(). I recall having a problem with there being extra commas on the end of the string, but can't remember the situation where it was happening.Hebrides
S
9

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
Summer answered 22/10, 2014 at 7:15 Comment(0)
P
4

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."
        }
Preferment answered 5/2, 2014 at 14:46 Comment(0)
R
4
$fruit = array('apple', 'banana', 'pear', 'grape');    
$commasaprated = implode(',' , $fruit);
Redblooded answered 2/11, 2016 at 10:40 Comment(1)
The most simple answer. Why write tens of lines when you can do it in 1 line of code.Centistere
N
3

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 ", ";
    }
}
Nigelniger answered 8/11, 2012 at 14:56 Comment(1)
if the total count is just different than 4 ?Figurehead
P
1

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.

Palanquin answered 13/3, 2014 at 18:7 Comment(0)
M
0

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);
    },
    ''
);
Metempirics answered 10/2, 2017 at 13:21 Comment(0)
P
0

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;
Patrizius answered 27/3, 2020 at 18:33 Comment(0)
H
-1

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.

Holcman answered 27/1, 2014 at 11:41 Comment(0)
A
-2
$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

Allegro answered 22/4, 2014 at 8:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.