In PHP, sometimes we need to concatenate elements in an array and use commas as separators.
For this problem, PHP provides a variety of solutions. Let us introduce them one by one.
Method 1: Loop traversal
The first method is to use a for loop to traverse the array and connect each element in turn, and finally use the implode() function to connect them. The code is as follows:
$arr = array('apple', 'banana', 'orange', 'pear'); $str = ''; for($i = 0; $i < count($arr); $i++){ if($i != 0){ $str .= ','; } $str .= $arr[$i]; } echo $str;
This code will output:
apple, banana, orange, pear
Method 2: Use the implode() function
The simpler way of this code is to use implode( ) function. The implode() function concatenates elements in an array into a string and inserts a delimiter between them.
$arr = array('apple', 'banana', 'orange', 'pear'); $str = implode(',', $arr); echo $str;
This code will also output:
apple, banana, orange, pear
Method 3: Use the join() function
The join() function has the same function as the implode() function. The only difference between the two functions is the order of their parameters.
$arr = array('apple', 'banana', 'orange', 'pear'); $str = join(',', $arr); echo $str;
Similarly, this code will also output:
apple, banana, orange, pear
The above are three methods of converting arrays into comma delimiters. No matter which method, you can easily convert The elements in the array are concatenated and separated by commas.
The above is the detailed content of How to convert array to comma separated string in php. For more information, please follow other related articles on the PHP Chinese website!