This guide will teach you how khổng lồ convert an array of values to lớn a comma-separated string.
The Basics – An Array
Let us start by understanding a PHP array & how we can use it in our programs. Feel không tính tiền to skip this section if you are versed in how PHP arrays work.
Bạn đang xem: How to create comma separated list from an array in php
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 lớn store related information. For example, you can store information related khổng lồ 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", "
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. Kiểm tra the documentation and other resources lớn learn more.
Introduction khổng lồ PHP Implode Function
We will use the implode function to lớn convert an array to a string of comma-separated values. This function allows you to lớn take an array and convert it lớn a string where a specified delimiter separates individual values.
The function’s syntax is as shown:
implode(string $separator, array $array)
It takes a separator & an array as the arguments.
The function returns a string of values separated by the phối delimiter.
Convert Array to lớn Comma Separated String
To convert an array of items lớn a string, we can use the implode function and pass the array and a comma as the delimiter.
Consider the example shown below:
$databases = array("MySQL", "Redis", "MongoDB", "PostgreSQL", "SQLite"); print_r($databases); $imploded_string = implode(",", $databases); print_r($imploded_string);?>
In the example code above, we create an array that holds various databases. Next, we use the implode function to convert the collection to lớn a comma-separated string.
Once you run the code, you should see the output as shown:
$ php implode.php