Search code examples
phpforeachdelimited

Convert array to comma-delimited string without trailing comma


Quick PHP problem here :

When doing a for each statement I have to echo it in a perticular syntax I.E

|First_Name:bob,jim,alex,gary|Last_Name:Smith,Doe,foo|Age:11,12,13

I have so far manage to achieve this syntax except for the last value of each of the for loop as I get this result

|First_Name:bob,jim,alex,gary,|Last_Name:Smith,Doe,foo,|Age:11,12,13,

so the is an extra comma in every itteration of the second loop.

Is there a way to get rid of the comma for the last value only.


Solution

  • There is a built-in function for joining array elements, called implode, which I suggest you should use:

    $a = [1, 2, 3];
    $s = implode(",", $a);
    
    // result: "1,2,3"
    

    NB: The short array notation was introduced in PHP 5.4. For older versions, use this line instead to initialize an array:

    $a = array(1, 2, 3);