In PHP, sometimes we need to convert comma-separated strings into arrays. Let's say we got a set of data from the database separated by commas, but we want to convert it into an array so that we can operate on it more conveniently.
In PHP, a comma-separated string can be converted into an array through the explode() function. The usage of this function is very simple. You only need to pass two parameters in the function: the delimiter and the string to be split.
The following is a sample code:
$str = "apple,banana,grape,orange"; $arr = explode(",", $str); print_r($arr);
The output result is as follows:
Array ( [0] => apple [1] => banana [2] => grape [3] => orange )
In the above code, we use commas as the delimiter and replace the string "apple,banana, grape,orange" is passed to the explode() function. The function returns an array in which the delimiter "," is used to split the string, and the resulting array contains four elements.
In addition to using commas as delimiters, we can also use other symbols as delimiters. For example, in the following sample code, we use spaces as delimiters:
$str = "apple banana grape orange"; $arr = explode(" ", $str); print_r($arr);
The output result is as follows:
Array ( [0] => apple [1] => banana [2] => grape [3] => orange )
In addition to converting strings into arrays, we can also use implode() The function converts the array into a string and connects each element using the specified delimiter. The specific usage method is opposite to the explode() function. The example is as follows:
$arr = array("apple", "banana", "grape", "orange"); $str = implode(",", $arr); echo $str;
The output result is as follows:
apple,banana,grape,orange
In short, to convert a comma-separated string into an array, you only need to use the explode() function, passing the delimiter and the string to be converted as parameters. In addition, if you need to convert the array into a comma-separated string, you can use the implode() function, and you also need to pass the delimiter and array as parameters. The conversion between comma-separated strings and arrays is very simple and easy to understand in PHP, and we can use it flexibly in actual development.
The above is the detailed content of php comma to array. For more information, please follow other related articles on the PHP Chinese website!