This guide will teach you how to convert an array of values to a comma-separated string.
The Basics – An Array
Let us start by understanding a PHP array and how we can use it in our programs. Feel free to skip this section if you are versed in how PHP arrays work.
In simple terms, an array is a variable that can hold multiple values of the same type. A typical use case of an Array is to store related information. For example, you can store information related to a user in an array.
We use the array() function to create an array in PHP. Consider the example below that illustrates creating a simple Array in PHP.
$user = array("John Doe", "firstname.lastname@example.org", "3000$");
The code above creates a simple array showing information related to a specific user.
There are various arrays in PHP, such as associative, multidimensional arrays. We will not discuss them in this tutorial as they are out of the scope of this guide. Check the documentation and other resources to learn more.
Introduction to PHP Implode Function
We will use the implode function to convert an array to a string of comma-separated values. This function allows you to take an array and convert it to a string where a specified delimiter separates individual values.
The function’s syntax is as shown:
It takes a separator and an array as the arguments.
The function returns a string of values separated by the set delimiter.
Convert Array to Comma Separated String
To convert an array of items to a string, we can use the implode function and pass the array and a comma as the delimiter.
Consider the example shown below:
In the example code above, we create an array that holds various databases. Next, we use the implode function to convert the collection to a comma-separated string.
Once you run the code, you should see the output as shown:
The following example shows how to pass a comma and space as the delimiter.
The code above should return the elements in the array separated by a comma and space.
Does the function work on a multidimensional array? Simple answer, no. The function cannot implode multidimensional array as shown:
PHP will return “Array to string conversion” if you run the code above.
This tutorial shows you how to use the PHP implode function to create a string of comma-separated values. The implode function has an alias of join(), which you can perform the same task.
Thank you for reading!