Turn a PHP array or object into a comma separated string

Often times when coding in PHP, we have the need to turn an array into a comma separated string, or even an object into a comma separated string. As a Florida PHP Developer, I’d like to save you some time and show you the code.

Simple PHP array to comma separated string

That’s the basic way of doing it. But what if you have an associated array?

Associated array to comma separated string

That grabs the array values and turns them into a comma separated string. I added a variable to the function, $glue, in case you want to join the array by a different value.

We can also take this a step further and turn the array keys of the associated array into a comma separated array:

This is a simple way of doing it. I added a parameter to the function $type and when set to keys it will spit out the keys instead of the array values.

PHP array of objects to comma separated string

We can overly complicate one function, or just write a new one for objects. This will work with objects or associated arrays as long as you pass in the $field parameter and set it to the field you want to use for the comma separated string.

Again, you can change the $glue parameter and then have it be another type of string. This function will skip objects or arrays that do not have the $field you specified.

Conclusion

You just learned how to turn a simple PHP array into a comma separated string, and you also learned how to turn associated arrays/objects into a comma separated string. It’s up to you if you want to take this a step further and customize it to your needs. Be careful not to dump a whole bunch of data in there because you risk crashing your script.

Leave a Reply