TransWikia.com

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:

<?php

$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
$arr[2][0]
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
{$arr[2][0]}
EOT;

Output:

string 3

Demo on 3v4l.org

Correct answer by Nick on December 17, 2020

Use {} within the heredoc:

echo <<<EOT
{$arr[2][0]}
EOT;

output:

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!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP