How to convert array to comma separated string in php

PHPz
Release: 2023-04-13 09:59:38
Original
1529 people have browsed it

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;
Copy after login

This code will output:

apple, banana, orange, pear
Copy after login
Copy after login
Copy after login

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;
Copy after login

This code will also output:

apple, banana, orange, pear
Copy after login
Copy after login
Copy after login

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;
Copy after login

Similarly, this code will also output:

apple, banana, orange, pear
Copy after login
Copy after login
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template