18

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

6 Answers 6

46

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

Try

$groupIDStr = implode(',', $groupViewID);
Sign up to request clarification or add additional context in comments.

3 Comments

Excellent. Is there a variation that does implode, but start at $groupViewID[3] and go to the end? Thanks!
What you need to do is create a new array which contains everything from $groupViewID[3] to the end, and provide that to implode. In the above example, you can just replace $groupViewID with array_slice($groupViewID, 3).
Using PHP since the beginning. I still find parameter orders unnatural. I'd expect the subject first, like join [array] (with) [seperator], as the array is the most significant element in the operation.
9

You want implode:

implode(',', $array);

https://www.php.net/implode

Comments

7

implode()

$a = array('a','b','c');
echo implode(",", $a); // a,b,c

Comments

7
$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).

2 Comments

Even though join is correct as well, I think most PHP developers are used to seeing implode instead. :)
@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.
1

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

Comments

1

You can use implode() even with empty delimeter: implode(' ', $value); pretty convenient.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.