php array to string

PHP Array to String Conversion: 3 Methods

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);
separatorOptionalSpecifies what to put between the array elements. Default is "" (an empty string)
arrayRequiredSpecifies the array you want to convert
Returned ValueReturns 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 string by “,” 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()

In PHP, you can convert objects and an array into JSON String by using the PHP 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 array to string with PHP loops

To change the array to 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,'

Read More: