- PHP Convert Array to Comma Separated String
- How to Convert Array to Comma Separated String in PHP
- Method 1: Using implode() Function
- Syntax of using the PHP implode method
- Parameters of implode function:
- Examples – Convert an Array to String in PHP using implode function
- Method 2: Using foreach Loop
- Method 3: Using array_reduce() Function
- Conclusion
- Recommend PHP Tutorials
- Author Admin
- implode
- Parameters
- Return Values
- Changelog
- Examples
- Notes
- See Also
- User Contributed Notes 14 notes
PHP Convert Array to Comma Separated String
basically, in PHP you use implode function to convert the array into comma separated string. And with implode function convert one-dimensional, two-dimensional, and multidimensional arrays to comma separated strings. In this tutorial, you will learn how to convert an array to comma separated string using implode function.
To convert an array into a comma-separated string. This is a relatively simple task, but it can be confusing for beginners who are not familiar with the various functions and techniques that are available in PHP.
How to Convert Array to Comma Separated String in PHP
Here, you will explore the various methods of converting an array to a comma-separated string in PHP.
- Method 1: Using implode() Function
- Method 2: Using foreach Loop
- Method 3: Using array_reduce() Function
Method 1: Using implode() Function
The implode() function is a built-in PHP function that can be used to join the elements of an array into a string using a specified delimiter. To convert an array to a comma-separated string, you can use the implode() function with the comma (,) or quotes as the delimiter.
Syntax of using the PHP implode method
The basic syntax of the implode function is:
Parameters of implode function:
Examples – Convert an Array to String in PHP using implode function
Let’s see the following examples to convert one dimensional, two dimensional and multidimensional array to comma separated string in PHP:
- Example 1: PHP Array to String Conversion
- Example 2: PHP Array to Comma Separated String
- Example 3: PHP Two Dimensional Array Convert to Comma Separated String
- Example 4: PHP Implode – Multidimensional Array to Comma Separated String
Example 1: PHP Array to String Conversion
Let’s take an example for index array convert to string in PHP:
Example 2: PHP Array to Comma Separated String
Let’s take new example with an array, here you will convert array to a comma-separated string.
Example 3: PHP Two Dimensional Array Convert to Comma Separated String
Now will take the example of a two-dimensional array. In this example, you will convert two-dimensional array to comma separate string.
$result = implode(',', $tmpArr); echo $result;
Example 4: PHP Implode – Multidimensional Array to Comma Separated String
Here you will learn how you can convert multidimensional array to comma separated string.
'PHP', 'Email' => '[email protected]' ), array( 'Name' => 'Java', 'Email' => '[email protected]' ) ); echo implode(', ', array_map(function ($string) < return $string['Name']; >, $multi_dimensional_array)); ?>
Method 2: Using foreach Loop
Another method to convert an array into a comma-separated string is by using the foreach loop. This method is useful if you want to modify the array elements before joining them into a string. To convert an array into a comma-separated string using the foreach loop.
$fruits_string = rtrim($fruits_string, ","); echo $fruits_string; ?>
In the example above, you use a foreach loop to iterate through each element of the array, concatenate it with a comma, and append it to the $fruits_string variable. You use the rtrim() function to remove the trailing comma from the string.
Method 3: Using array_reduce() Function
The array_reduce() function is another built-in PHP function that can be used to reduce an array to a single value by applying a callback function to each element of the array. You can use the array_reduce() function to concatenate the elements of the array with a comma.
); $fruits_string = rtrim($fruits_string, ","); echo $fruits_string; ?>
In the example above, you use the array_reduce() function with a callback function that concatenates each element of the array with a comma. The first parameter of the callback function is the carry variable that stores the result of the previous iteration, and the second parameter is the current item of the array.
Conclusion
In this article, you have learned the various methods of converting an array into a comma-separated string in PHP. The most common method is using the implode() function, but you can also use the foreach loop or the array_reduce() function to achieve the same result. Each method has its advantages and disadvantages, so it’s important to choose the method that best suits your needs. With these techniques, you can easily convert arrays into comma-separated strings and use them in your PHP convert json array to comma separated string phpb applications.
Converting an array to a comma-separated string is a common task in PHP, and there are several methods to accomplish this. The most commonly used methods are the implode() function, a loop, and the array_reduce() function. By using any of these methods, you can easily convert an array to a comma-separated string and use it in your PHP applications.
Recommend PHP Tutorials
Author Admin
My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.
implode
Alternative signature (not supported with named arguments):
Legacy signature (deprecated as of PHP 7.4.0, removed as of PHP 8.0.0):
Join array elements with a separator string.
Parameters
Optional. Defaults to an empty string.
The array of strings to implode.
Return Values
Returns a string containing a string representation of all the array elements in the same order, with the separator string between each element.
Changelog
Version | Description |
---|---|
8.0.0 | Passing the separator after the array is no longer supported. |
7.4.0 | Passing the separator after the array (i.e. using the legacy signature) has been deprecated. |
Examples
Example #1 implode() example
$array = [ ‘lastname’ , ’email’ , ‘phone’ ];
var_dump ( implode ( «,» , $array )); // string(20) «lastname,email,phone»
// Empty string when using an empty array:
var_dump ( implode ( ‘hello’ , [])); // string(0) «»
// The separator is optional:
var_dump ( implode ([ ‘a’ , ‘b’ , ‘c’ ])); // string(3) «abc»
Notes
Note: This function is binary-safe.
See Also
- explode() — Split a string by a string
- preg_split() — Split string by a regular expression
- http_build_query() — Generate URL-encoded query string
User Contributed Notes 14 notes
it should be noted that an array with one or no elements works fine. for example:
$a1 = array( «1» , «2» , «3» );
$a2 = array( «a» );
$a3 = array();
echo «a1 is: ‘» . implode ( «‘,'» , $a1 ). «‘
» ;
echo «a2 is: ‘» . implode ( «‘,'» , $a2 ). «‘
» ;
echo «a3 is: ‘» . implode ( «‘,'» , $a3 ). «‘
» ;
?>
will produce:
===========
a1 is: ‘1’,’2′,’3′
a2 is: ‘a’
a3 is: »
It’s not obvious from the samples, if/how associative arrays are handled. The «implode» function acts on the array «values», disregarding any keys:
$a = array( ‘one’ , ‘two’ , ‘three’ );
$b = array( ‘1st’ => ‘four’ , ‘five’ , ‘3rd’ => ‘six’ );
echo implode ( ‘,’ , $a ), ‘/’ , implode ( ‘,’ , $b );
?>
outputs:
one,two,three/four,five,six
Can also be used for building tags or complex lists, like the following:
?>
This is just an example, you can create a lot more just finding the right glue! 😉
It might be worthwhile noting that the array supplied to implode() can contain objects, provided the objects implement the __toString() method.
class Foo
protected $title ;
public function __construct ( $title )
$this -> title = $title ;
>
public function __toString ()
return $this -> title ;
>
>
$array = [
new Foo ( ‘foo’ ),
new Foo ( ‘bar’ ),
new Foo ( ‘qux’ )
];
echo implode ( ‘; ‘ , $array );
?>
will output:
If you want to implode an array of booleans, you will get a strange result:
var_dump ( implode ( » ,array( true , true , false , false , true )));
?>
Output:
string(3) «111»
TRUE became «1», FALSE became nothing.
If you want to implode an array as key-value pairs, this method comes in handy.
The third parameter is the symbol to be used between key and value.
function mapped_implode ( $glue , $array , $symbol = ‘=’ ) return implode ( $glue , array_map (
function( $k , $v ) use( $symbol ) <
return $k . $symbol . $v ;
>,
array_keys ( $array ),
array_values ( $array )
)
);
>
echo mapped_implode ( ‘, ‘ , $arr , ‘ is ‘ );
// output: x is 5, y is 7, z is 99, hello is World, 7 is Foo
Sometimes it’s necessary to add a string not just between the items, but before or after too, and proper handling of zero items is also needed.
In this case, simply prepending/appending the separator next to implode() is not enough, so I made this little helper function.
function wrap_implode ( $array , $before = » , $after = » , $separator = » ) if( ! $array ) return » ;
return $before . implode ( » < $after >< $separator > < $before >» , $array ) . $after ;
>
echo wrap_implode ([ ‘path’ , ‘to’ , ‘file.php’ ], ‘/’ );
// «/path/to/file.php»
$pattern = ‘#’ . wrap_implode ([ 4 , 2 , 2 ], ‘\d’ , ‘[-.]’ ) . ‘#’ ;
echo $pattern , «\n» ; // #\d[-.]\d[-.]\d#
echo preg_replace ( $pattern , ‘[REDACTED]’ , ‘The UFO appeared between 2012-12-24 and 2013.01.06 every night.’ );
// ‘The UFO appeared between [REDACTED] and [REDACTED] every night.
echo wrap_implode ([ ‘line’ , ‘by’ , ‘line’ ], ‘‘ , ‘‘ , ‘
‘ );
// line
by
line
It may be worth noting that if you accidentally call implode on a string rather than an array, you do NOT get your string back, you get NULL:
var_dump ( implode ( ‘:’ , ‘xxxxx’ ));
?>
returns
NULL
This threw me for a little while.
Even handier if you use the following:
$id_nums = array( 1 , 6 , 12 , 18 , 24 );
$id_nums = implode ( «, » , $id_nums );
$sqlquery = «Select name,email,phone from usertable where user_id IN ( $id_nums )» ;
// $sqlquery becomes «Select name,email,phone from usertable where user_id IN (1,6,12,18,24)»
?>
Be sure to escape/sanitize/use prepared statements if you get the ids from users.
null values are imploded too. You can use array_filter() to sort out null values.
$ar = array( «hello» , null , «world» );
print( implode ( ‘,’ , $ar )); // hello,,world
print( implode ( ‘,’ , array_filter ( $ar , function( $v )< return $v !== null ; >))); // hello,world
?>
If you want to use a key inside array:
Example:
$arr=array(
array(«id» => 1,»name» => «Test1»),
array(«id» => 2,»name» => «Test2»),
);
echo implode_key(«,»,$arr, «name»);
OUTPUT: Test1, Test2
function implode_key($glue, $arr, $key) $arr2=array();
foreach($arr as $f) if(!isset($f[$key])) continue;
$arr2[]=$f[$key];
>
return implode($glue, $arr2);
>
It is possible for an array to have numeric values, as well as string values. Implode will convert all numeric array elements to strings.
$test = implode ([ «one» , 2 , 3 , «four» , 5.67 ]);
echo $test ;
//outputs: «one23four5.67»
?>
There is no mention of behavior on a empty array, so I tried it and here’s the result:
$ar = array();
$result = implode ( ‘,’ , $ar ); // Comma arbitrarily applied as the separator
$is_result_empty = empty( $result );
?>
$result:
$is_result_empty: 1
In other words, an empty string is the result.
* Join pieces with a string recursively .
*
* @ param mixed $glue String between pairs ( glue ) or an array pair ‘s glue and key/value glue or $pieces.
* @param iterable $pieces Pieces to implode (optional).
* @return string Joined string
*/
function double_implode($glue, iterable $pieces = null): string
$glue2 = null;
if ($pieces === null) $pieces = $glue;
$glue = »;
> elseif (is_array($glue)) list($glue, $glue2) = $glue;
>
?php
$result = [];
foreach ($pieces as $key => $value) $result[] = $glue2 === null ? $value : $key . $glue2 . $value;
>
return implode($glue, $result);
>
?>
Examples:
$array = [‘ a ‘ => 1, ‘b’ => 2];
$str = implode($array);
$str = implode(‘ , ‘, $array);
$str = implode([‘» ‘, ‘ keyword»>, ‘, $iterator);
$str = implode([‘» ‘, ‘ foot»>+add a note