Converting an array to a string can be done in several methods like PHP loops or built-in functions like implode() and json_encode(). In this tutorial, we are going to discuss how to convert an array to a string or JSON in PHP.
PHP array to string conversion content
Using implode() Function
This function returns a string from the elements of an array. The separator parameter in implode() function is optional.
implode(separator, array);
| separator | Optional | Specifies what to put between the array elements. Default is "" (an empty string) |
| array | Required | Specifies the array you want to convert |
| Returned Value | Returns a string from elements of an array |
This function is available since PHP version 4.
Example
$cars = array('Ferrari', 'Benz', 'BMW', 'Volvo');
var_dump(implode(",", $cars));
Output
'Ferrari,Benz,BMW,Volvo'
In this example, the array is converted to a string with a “,” separator. If you don’t define the separator, the array items will convert to strings without any separator.
$cars = array('Ferrari', 'Benz', 'BMW', 'Volvo');
var_dump(implode($cars));
Output
'FerrariBenzBMWVolvo'
There is no difference between the Indexed array and associative array in implode() function because this function only converts the values of the array, not the keys.
Convert PHP array to JSON using json_encode()
You can convert objects and an array into a JSON String by using the built-in function json_encode(). You can convert an array to a string with the json_encode() function, too, but the string will be in JSON format.
$cars = array('Ferrari', 'Benz', 'BMW', 'Volvo');
var_dump(json_encode($cars));
Output
'["Ferrari","Benz","BMW","Volvo"]'
Convert an array to a string with PHP loops
To change the array to a string using loops, like for or foreach loop, you have to do a little more effort.
$cars = array('Ferrari', 'Benz', 'BMW', 'Volvo');
$str = '';
foreach ($cars as $car) {
$str .= $car . ",";
}
var_dump($str);
Output
'Ferrari,Benz,BMW,Volvo,'
FAQ
What is the best way to convert an array to a string in PHP?
The best way to convert is the implode() function. This function converts an array to a string with a separator.
