Skip to content
Happy Programming Guide
Start learning
PHP

Fixing “Array to string conversion” in PHP

You used an array where PHP expected a string: in echo, concatenation, a database query or a function argument. Where the warning comes from, and the right way to turn an array into text.

Network cables plugged into a switch

Warning: Array to string conversion means PHP was asked to treat an array as a string — to echo it, join it to another string, put it in a query, or pass it to a function that wants text — and did the only thing it could: substituted the literal word Array and warned. The output is wrong wherever that happened. The fix depends on what you meant: print the array for debugging, join its items, or pick one element out of it.

What is happening#

PHP
$tags = ['php', 'arrays'];
echo "Tags: " . $tags;          // Warning: Array to string conversion
                                // prints: Tags: Array

PHP cannot invent a text form for an array, so it uses the word Array and raises a warning to tell you. Since PHP 8 it is a warning rather than a notice, so it is more visible; the behaviour is the same.

Cause 1: you wanted to see the array#

For debugging, use the functions built for it:

PHP
print_r($tags);                 // Array ( [0] => php [1] => arrays )
var_dump($tags);                // with types and lengths
echo '<pre>' . print_r($tags, true) . '</pre>';   // readable in a browser
error_log(print_r($tags, true));                    // into the log

var_export produces valid PHP syntax, useful for pasting into code or a config file.

Cause 2: you wanted the items as text#

PHP
echo "Tags: " . implode(', ', $tags);      // Tags: php, arrays
echo json_encode($tags);                    // ["php","arrays"]

implode joins the values with a separator. For nested arrays, or when the output is for a machine, json_encode is the honest representation.

Cause 3: you wanted one element#

PHP
$user = ['name' => 'Ann', 'roles' => ['admin', 'editor']];

echo "Hello $user";                     // Array to string conversion
echo "Hello " . $user['name'];          // Hello Ann
echo "Hello {$user['name']}";           // the same, inside a string
echo "Roles: " . $user['roles'];        // still an array! implode it

Interpolation has a trap: "$user['name']" without braces is a parse error, and "$user[name]" works but is fragile. The braced form {$user['name']} is the reliable one.

Cause 4: form fields and query strings#

HTML
<input type="checkbox" name="colours[]" value="red">
<input type="checkbox" name="colours[]" value="blue">
PHP
$colours = $_POST['colours'];           // an array, because of the []
echo "You chose " . $colours;           // Array to string conversion
echo "You chose " . implode(' and ', $colours);

A field name ending in [], a multi-select, or a query string like ?id[]=1&id[]=2 arrives as an array. Code that assumes a string gets this warning. Validate the shape: check is_array($value) and handle both cases, since a user can send either.

Cause 5: database queries#

PHP
$ids = [1, 2, 3];
$sql = "SELECT * FROM posts WHERE id IN ($ids)";           // Array to string conversion: IN (Array)

Build the placeholders and pass the values separately:

PHP
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$stmt = $pdo->prepare("SELECT * FROM posts WHERE id IN ($placeholders)");
$stmt->execute($ids);

Never implode the values straight into the SQL; that is an injection hole. The placeholder pattern above keeps prepared statements intact.

Cause 6: a function that returns an array#

PHP
$parts = explode('/', $path);
echo "First part: " . $parts;            // explode returns an array
echo "First part: " . $parts[0];

Also preg_split, array_map, array_filter, str_split, range, and most functions with “array” in the name. Check what the function returns, and index into it or implode it.

Finding the line#

The warning includes the file and line number. If errors are not displayed, they are in the log; turn on display_errors in development so the warning appears next to the wrong output. Then var_dump the variable on that line to confirm it is an array and see its shape.

Questions people ask#

Why does PHP not just throw an error?

Backwards compatibility. It has warned rather than failed since the early days; PHP 8 promoted it from notice to warning. It may become an error in a future major version.

Can I define how my object converts to a string?

For objects, yes: implement __toString(). Plain arrays cannot be given a string form; convert them explicitly.

What about nested arrays with implode?

implode only joins one level; a nested array inside triggers the same warning. Use json_encode, or map the inner arrays to strings first.

Is this the same as “Array to string conversion” in a JSON response?

If json_encode is used, arrays convert correctly. The warning appears when something concatenates the array before it reaches json_encode.

Where to go next#

Logging an array in PHP: print_r, var_export and error_logRead next

Keep reading

PHP

PHP Performance Optimization

Where PHP applications actually spend their time, how to measure before you optimise, and the fixes that matter: OPcache, N+1 queries, indexes…

5 min read

PHP

Working with APIs in PHP

Call a REST API from PHP with cURL or Guzzle, handle JSON and errors properly, add authentication, and build a small API…

4 min read

PHP

PHP PDO Explained With Examples

PDO is the standard way to talk to a database from PHP. Connecting, prepared statements that stop SQL injection, fetching rows, transactions…

5 min read

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *