Fixes & guides

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
  1. implode(): join values with a separator
  2. “Array to string conversion” warning
  3. json_encode(): the default for storing and sending
  4. serialize(): exact PHP round trips
  5. var_export() and print_r()
  6. Converting a string back to an array

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() without allowed_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.

Found a mistake or something out of date? Tell us and we will fix it. See our editorial policy.

A good place to start

What are you working on?

Tools, guides, PHP versions and the archive.

ToolJSON ↔ PHP arrayConvert JSON to a PHP array literal with short or array() syntax, or turn a PHP array back into JSON. Runs in your browser; nothing is uploaded.ToolSerialize / unserializeRead PHP serialized strings as a tree, repair wrong string lengths after a search-and-replace, or serialize a PHP array or JSON. Parsed safely in your browser.ToolComposer constraint testerSee exactly which versions a Composer constraint such as ^2.1, ~1.4 or >=8.1 <8.4 allows, in plain English, and test versions against it.ToolPHP date() format builderBuild a PHP date() or DateTime::format() string with a live preview in any time zone, plus a reference for every format character.ToolBcrypt generatorGenerate a bcrypt hash with a cost slider and verify a password against an existing hash. Output matches PHP password_hash() and password_verify(). Runs in your browser.ToolPHP version checkerPaste PHP code and see the minimum version it needs, the line that decided it, and any removed functions that cap the newest version it can run on.ToolCrontab generatorBuild a cron expression with presets, read it in plain English, see the next run times, and copy the crontab line or the matching Laravel scheduler call.ToolPHP upgrade checklistPick your current and target PHP versions and get every breaking change, deprecation and tooling step in between, as a checklist you can copy.GuideAllowed memory size exhaustedWhat PHP's memory_limit fatal error means, how to tell a real leak from a big job, and fixes for the usual causes: loading whole tables, unbounded arrays, Composer and recursion.GuideComposer dependency conflictsA step-by-step way to read Composer's conflict output, find the package that is blocking you, and fix it without --ignore-platform-reqs or deleting the lock file.Guidecomposer install vs updatecomposer install reproduces composer.lock; composer update rewrites it. Here is what each command does, when to use which, and a safe production deploy routine.GuideComposer uses the wrong PHP versionComposer says "your php version (8.1.x) does not satisfy that requirement" when your server runs 8.3? The cause is usually the CLI binary, config.platform.php, or platform_check.php.GuideEloquent N+1 queriesHow to spot N+1 queries in Laravel, fix them with eager loading, withCount() and constrained loads, and make Laravel throw an exception the next time one slips in.GuideHeaders already sentThe warning names the file and line that produced output. Here is how to read it, the five usual culprits (BOM, whitespace, echo, warnings, closing tags) and fixes that do not just hide it.GuideWriting a talk proposalWhat reviewers look for in a call-for-papers submission: a specific title, an abstract for attendees, notes for the committee, and a talk-sized idea. With a worked example and a checklist.GuideLaravel queue jobs not runningJobs dispatched but never processed, stuck in the jobs table, or running old code? Work through the connection, the queue name, the worker, failed jobs and deploy restarts.PHP versionsWhat's new in PHP 8.4PHP 8.4 (released 21 November 2024) brought property hooks, public private(set) visibility, new without parentheses, lazy objects, an HTML5 DOM parser and array_find(). Plus the deprecations that matter.PHP versionsWhat's new in PHP 8.5PHP 8.5 (released 20 November 2025) added the |> pipe operator, a standards-compliant URI extension, clone() with property overrides, #[\NoDiscard] and array_first()/array_last().PHP versionsWhat's new in PHP 8.6PHP 8.6 was released on 19 November 2026. Partial function application, clamp(), readonly property defaults, Io\Poll and Time\Duration, plus the session and ValueError changes to check before upgrading.GuidePHP array_filterHow array_filter() decides what to keep, why it removes "0" without a callback, how to filter by key or by key and value, and why the result needs array_values() before you treat it as a list.GuidePHP array_mapHow array_map() treats keys, how to map with the key as well as the value, what happens with several arrays or a null callback, and when a plain foreach or array_walk() is the better choice.GuidePHP array to JSONWhy json_encode() sometimes gives you an object instead of a list, how to keep floats and slashes intact, and how to catch the silent false that malformed UTF-8 returns.GuidePHP array to stringThree 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.GuidePHP FibersPHP 8.1 Fibers let a function pause and resume without returning. Here is how start, suspend and resume pass values, how Fibers differ from generators and threads, and where they help in real code.GuidePHP in_arrayWhy in_array() can return true for values that are not in the array, what changed in PHP 8, when to pass strict = true, and how to replace slow in_array() calls with isset() lookups.GuideInterface vs abstract classInterfaces define what a class can do; abstract classes share how it is done. A side-by-side table, examples of each, the common pattern of using both, and what PHP 8.1 to 8.4 changed for interfaces.GuidePHP sort arrayWhich PHP sort function to use, in one table: by value or key, keep keys or not, ascending or descending, or with your own comparison. Plus sorting by a column, by several fields and naturally.GuideDuplicate webhooks in PHPWebhook providers retry, so the same event can arrive twice. Verify the signature, record the event ID with a unique key, answer fast and process in a queue: a pattern that works in plain PHP, Laravel and Symfony.GuidePHPStan baseline for legacy codeGenerate a PHPStan baseline, stop new errors from getting in, then raise the level step by step. A tested routine for old PHP codebases.GuidePSR-4 autoloadingHow PSR-4 maps namespaces to folders, how to configure it in composer.json, and why "Class not found" happens: case, typos, a stale autoloader or a namespace that does not match the path.GuideSerialized data broken after search-replaceChanging a domain name with SQL REPLACE() or sed corrupts PHP serialized strings because their byte lengths no longer match. Here is how to spot it and repair it safely.GuideUpgrade PHP with RectorUpgrade a PHP application one version at a time: pin the baseline, let Rector rewrite syntax, let PHPStan find what Rector cannot, and prove it with tests before you switch runtimes.PHP versionsSupported PHP versionsRelease, active support and end-of-life dates for every PHP version.ArchiveSunshinePHP talk archive 2013–2020Talk titles and speakers from eight years of the Miami PHP conference.ArchiveSpeaker indexEveryone who spoke at SunshinePHP, A to Z.