Home  >  Article  >  Backend Development  >  How to convert array to comma separated string in php

How to convert array to comma separated string in php

PHPz
PHPzOriginal
2023-04-13 09:21:061499browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn