How do I convert an array to a string in PHP?

To convert an array to a string in PHP, you can use one of the following functions: implode(separator, array), json_encode(array), and serialize(array). The implode() method allow you to concatenate array elements into a single string. To do this, pass an array and a delimiter to the implode() method; the separator will be inserted between the array values. The json_encode() method converts an array to a JSON string. It takes an array as input and returns a JSON representation of the array. The serialize() method takes an array and converts it to a string. The method is handy if you want to store something in the database and retrieve it for later use. In this Convert PHP Array to String example, we use the implode() method to convert an array to a string. Below you can see more examples of converting PHP array to strings, detailing each method. Click Execute to run the PHP Array to String Example online and see the result.
How do I convert an array to a string in PHP? Execute
<?php
$array = array('PHP','array', 'to', 'string', 'conversion', 'example');
    
echo implode(' ', $array);
?>
Updated: Viewed: 922 times

How to convert an array to a string using the implode() function in PHP?

To convert an array to a string using PHP implode() function, you must pass a delimiter as the first argument and an array as the second.

PHP implode() Syntax
implode(separator, array)

Where:
  • separator (optional): character to be inserted between array elements. The default is an empty string.
  • array: array to convert to string
Convert PHP array to string using the implode()
<?php
$array = array('I','like', 'PHP');
         
echo implode('-', $array);
?>

#output: I-like-PHP

How to convert array to JSON string using PHP?

To convert an array to a JSON string with PHP, you can use the json_encode() function, which takes an array as input and converts it to JSON.

Convert PHP array to JSON string Example
<?php
$array = array(
    'Name' => 'Leo',
    'Age' => 25,
);

echo $json = json_encode($array); 
?>

#output: {"Name":"Leo","Age":25}

How to serialize array in PHP?

The serialize() function is to convert a variable (in our case, an array) into a storable state. The function saves the array to a string, which can then be converted back to an array in the future.

PHP Array serialize() Example
<?php
$array = array('apple', 'orange');

echo $string = serialize($array); ;
?>

#output: a:2:{i:0;s:5:"apple";i:1;s:6:"orange";}

See also