Throughout php implode function tutorial, you will learn, how to convert array to comma separated string in php. This tutorial explained you PHP Array to String Conversion, Two Dimensional Array to String Conversion, convert Multidimensional Array to Comma Separated String in php.
Let’s see php convert array to string using the PHP implode function.
PHP Implode Function
The basic syntax is of the implode function is:
implode(separator,array)
Parameters of implode function:
Parameter | Description |
---|---|
separator | Optional. Specifies what to put between the array elements. Default is “” (an empty string) |
array | Required. The array to join to a string |
PHP Convert Array to Comma Separated String
In PHP, The implode function is used to convert an array into a string.
We will learn in bellow example:
- PHP Array to String Conversion
- PHP Array to Comma Separated String
- PHP Two Dimensional Array Convert to Comma Separated String
- PHP Implode – Multidimensional Array to Comma Separated String
PHP Array to String Conversion
<?php
$array = array('php','laravel','codeigniter');
echo implode(" ",$array);
?>
Output:
php laravel codeigniter
PHP Array to Comma Separated String
This example convert array to a comma-separated string.
<?php
$array = array('php','laravel','codeigniter');
echo implode(", ",$array);
?>
Output:
php, laravel, codeigniter
Convert Two Dimensional Array to Comma Separated String
In this example, we will convert two-dimensional array to comma separate string.
<?php
// Two Dimensional array
$array = array (
array ('01','03','02','15'),
array ('05','04','06','10'),
array ('07','09','08','11')
);
$tmpArr = array();
foreach ($array as $sub) {
$tmpArr[] = implode(', ', $sub);
}
$result = implode(', ', $tmpArr);
echo $result;
?>
Output:
01, 03, 02, 15, 05, 04, 06, 10, 07, 09, 08, 11
Comma Multidimensional Array to Separated String
Let’s see how can convert multidimensional array to comma separated string.
<?php
$array = array(
array(
'name' => 'PHP',
'email' => 'php@gmail.com'
),
array(
'name' => 'Java',
'email' => 'java@gmail.com'
)
);
echo implode(', ', array_map(function ($string) {
return $string['name'];
}, $array));
?>
Output:
PHP, Java
So today you learn how to convert string to an array, two-dimensional array, and multi-dimensional in PHP.