Array to string conversion when using heredoc syntax

Stack Overflow Asked by icecub on December 17, 2020

I’m running into a weird issue where it seems I can’t echo out an array value using heredoc syntax:


$arr = array(
    array("string 1"),
    array("string 2"),
    array("string 3")

// string 3
echo $arr[2][0];

// Notice: Array to string conversion
// Var dump: string(8) "Array[0]"
echo <<<EOT

I feel like this is something I should know by now, but I can’t find any reason why this is happening or how to solve it. Anyone willing to enlighten me?

2 Answers

From the examples in the PHP manual on Strings:

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

Since heredoc syntax is equivalent to a quoted string, you need to use braces around the value:

echo <<<EOT


string 3

Demo on

Correct answer by Nick on December 17, 2020

Use {} within the heredoc:

echo <<<EOT


string 3string 3

When it comes to having an array or object reference in the string needs complex parsing using the {}. Info from the link: (examples can be found there too)

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {$ to get a literal {$.

Answered by Paul T. on December 17, 2020

Add your own answers!

Related Questions

Polygons from line segments

3  Asked on November 27, 2021


JSLint: Disallow state. in Redux connect functon

0  Asked on November 27, 2021 by hakunin


Copy content of SQL Server 2016 db

4  Asked on November 27, 2021 by mjpolak


How to disable autofix for specific rules in eslint using CLI?

2  Asked on November 27, 2021 by chevybow


Managing multiple sites on XAMPP

1  Asked on November 27, 2021 by moeez


How to find what library provides the import?

1  Asked on November 27, 2021 by daneel-yaitskov


Wait for forEach with a promise inside to finish

2  Asked on November 27, 2021 by inbahn


Solving modular linear congruences for large numbers

2  Asked on November 27, 2021 by oppressionslayer


Sort 3D eigenvector array using eigenvalues

1  Asked on November 27, 2021 by t-a


Interpolation of values from list

3  Asked on November 27, 2021


How can I delete a specific character from set of tuples?

2  Asked on November 27, 2021 by determindedelixir


Ask a Question

Get help from others!

© 2022 All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir