PHP array to string: implode vs json_encode vs serialize
Three ways to turn a PHP array into a string, and when to use each: implode() for display and CSV-like lists, json_encode() for APIs and storage, serialize() for PHP-only data. Plus the Array to string conversion warning.
On this page
There is no single “array to string” function in PHP, because the right string depends on what happens to it next. A person reading it, a JavaScript client and a PHP cache all want different formats.
| You need | Use | Example output | Back to an array |
|---|---|---|---|
| A readable list | implode() |
red, green, blue |
explode() |
| Data for an API, a database column or JavaScript | json_encode() |
["red","green","blue"] |
json_decode($s, true) |
| PHP-only storage that keeps exact types | serialize() |
a:3:{i:0;s:3:"red";…} |
unserialize() |
| Valid PHP code | var_export($a, true) |
array (0 => 'red', …) |
include the file |
| Debug output | print_r($a, true) |
Array ( [0] => red … ) |
not meant to be read back |
| A query string | http_build_query() |
color=red&size=m |
parse_str() |
implode(): join values with a separator
$colors = ['red', 'green', 'blue'];
echo implode(', ', $colors); // red, green, blue
echo implode($colors); // redgreenblue (empty separator)
The separator comes first. The old reversed order, implode($array, ', '), was deprecated in PHP 7.4 and removed in PHP 8.0, so it now throws a TypeError. join() is an alias of implode().
implode() uses only the values. To include keys, build the pieces first:
$attrs = ['class' => 'btn', 'type' => 'submit'];
echo implode(' ', array_map(
fn ($key, $value) => sprintf('%s="%s"', $key, htmlspecialchars($value)),
array_keys($attrs),
$attrs,
));
// class="btn" type="submit"
More on that pattern in array_map with keys.
Values are converted with PHP’s normal string rules: true becomes "1", false and null become "", and floats use the shortest exact form. Nested arrays become the word Array with a warning, which brings us to the most common error.
“Array to string conversion” warning
Warning: Array to string conversion in /app/src/Report.php on line 42
PHP raised this as a notice before 8.0 and as a warning since. It means an array was used where a string was expected: echo $array, "Total: $array", string concatenation with ., or implode() on an array that contains arrays. The output is the literal word Array, which is never what you meant.
Find the line, then decide which format you actually want from the table above. For nested data, that is almost always json_encode(). To print something while debugging, use print_r($value, true) or var_dump().
json_encode(): the default for storing and sending
$order = ['id' => 42, 'items' => ['tea', 'scone'], 'paid' => true];
$json = json_encode($order, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
// {"id":42,"items":["tea","scone"],"paid":true}
$back = json_decode($json, true, flags: JSON_THROW_ON_ERROR);
JSON is readable, every language can parse it, and databases such as MySQL and PostgreSQL can query inside a JSON column. Its weaknesses are small but real: objects lose their class, floats like 10.0 become 10 unless you add JSON_PRESERVE_ZERO_FRACTION, and a PHP array with keys that are not 0, 1, 2… becomes a JSON object. The details and fixes are in PHP array to JSON.
serialize(): exact PHP round trips
$s = serialize(['price' => 10.0, 'tags' => ['a'], 'at' => new DateTimeImmutable('2026-12-05')]);
$back = unserialize($s, ['allowed_classes' => [DateTimeImmutable::class]]);
serialize() keeps PHP types exactly: integers, floats, null, nested arrays and objects with their class. That makes it suitable for caches and sessions that only PHP reads. It has two serious downsides:
- Security. Never pass untrusted input to
unserialize()withoutallowed_classes. Restoring objects can trigger magic methods on any loaded class, which is how PHP object injection works. - Fragility. Every string is stored with its length in bytes. A find-and-replace on a database dump changes the text but not the length, and the value can no longer be read. That is why WordPress migrations need special tools.
The serialize and unserialize tool shows a serialized value as a tree, repairs broken lengths, and can serialize a PHP array or JSON for you. For new data shared with anything other than PHP, use JSON.
var_export() and print_r()
var_export($array, true) returns valid PHP source code, which you can write to a file and later include. It is how many frameworks cache configuration:
file_put_contents('cache/config.php', '<?php return ' . var_export($config, true) . ';');
$config = include 'cache/config.php';
print_r($array, true) returns a human-friendly dump for logs. The true argument makes both functions return the string instead of printing it.
Converting a string back to an array
| String made with | Reverse with | Watch out for |
|---|---|---|
implode(',', $a) |
explode(',', $s) |
Values that contained the separator; empty string gives [''] |
json_encode($a) |
json_decode($s, true) |
Without true you get stdClass objects |
serialize($a) |
unserialize($s, ['allowed_classes' => false]) |
Untrusted input, broken lengths |
http_build_query($a) |
parse_str($s, $result) |
Always pass the second argument |
For lists that users type, array_filter(array_map('trim', explode(',', $input))) splits, trims and drops empty entries in one line. Remember that array_filter() keeps the original keys; see array_filter.