Converting Array to 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() function allows you to concatenate array elements into a single string. To do this, pass an array, and a delimiter to the implode(); the separator will be inserted between the array values. The json_encode() function converts an array to a JSON string. It takes an array as input and returns a JSON array representation. The serialize() function takes an array and converts it to a string. This function 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() function to convert an array to a string. Below you can see more examples of converting a PHP array to a string with a detailed description of each method. Click Execute to run the PHP Array to String Example online and see the result.
Converting Array to String in PHP Execute
<?php
$array = array('PHP','array', 'to', 'string', 'conversion', 'example');
    
echo implode(' ', $array);
?>
Updated: Viewed: 1826 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