tags:

views:

1055

answers:

5

Is there a quick way ( existing method) Concatenate array element into string with ',' as the separator? Specifically I am looking for a single line of method replacing the following routine:

    //given ('a','b','c'), it will return 'a,b,c'
private static function ConstructArrayConcantenate($groupViewID)
{
 $groupIDStr='';
  foreach ($groupViewID as $key=>$value)
 {
  $groupIDStr=$groupIDStr.$value;
  if($key!=count($groupViewID)-1)
    $groupIDStr=$groupIDStr.',';

 }  

 return $groupIDStr;
}
+8  A: 

You want implode:

implode(',', $array);

http://us2.php.net/implode

carl
+5  A: 

implode()

$a = array('a','b','c');
echo implode(",", $a); // a,b,c
cpharmston
+10  A: 

This is exactly what the PHP implode() function is for.

Try

$groupIDStr = implode(',', $groupViewID);
Artelius
+4  A: 
$arr = array('a','b','c');
$str = join(',',$arr);

join is an alias for implode, however I prefer it as it makes more sense to those from a Java or Perl background (and others).

karim79
Even though join is correct as well, I think most PHP developers are used to seeing implode instead. :)
carl
@Carl Vondrick - all the more reason to use join() IMO, but I can understand that PHP developers would prefer to use implode(), as it *does* sound cooler.
karim79
A: 

implode() function is the best way to do this. Additionally for the shake of related topic, you can use explode() function for making an array from a text like the following:

$text = '18:09:00'; $t_array = explode(':', $text);

Tareq