This is a short and simple PHP tutorial on how to convert an array of strings into a comma-delimited string. To do this, we will use PHP’s handy implode function.
Let’s assume that we have a PHP array of first names. Let’s also assume that we want to convert the elements of that array into one big comma-separated string.
Take a look at the following example:
//PHP array containing strings. //In this cases, it's an array of first names. $array = array( 'Bob', 'Lisa', 'Michael', 'Marie', 'John' ); //Use the implode function to create a comma-delimited string. $str = implode(",", $array); //Print out our new string. echo $str; //Result is: //Bob,Lisa,Michael,Marie,John
In the code above, we used PHP’s implode function to convert the array elements into a comma-delimited string. The implode function takes in two arguments:
- The glue: This is the string that separates each element from our array. In this case, we chose a comma. By default, this parameter is an empty string unless you specify otherwise.
- The array of strings that you want to join together.
If you run the example yourself, you will see that the following string is printed out onto the page:
Bob,Lisa,Michael,Marie,John
If you want a comma and a space, then you can simply modify the glue parameter and add a space:
$str = implode(", ", $array);
If you want to delimit each string by a hyphen character, then you can do the following:
$str = implode("-", $array);
Note that if your array contains a non-scalar value, you will receive an error notice similar to this:
Notice: Array to string conversion
The notice above is telling me that there was an array inside my array and that implode could not properly convert it into a string. Thankfully, the function will handle float values and integers just fine!