0

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?

0

2 Answers 2

3

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 {$.

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome! This indeed solved the problem. Could you perhaps explain the reason behind this? Or point me to the docs?
Thank you :) I appreciate your help. I'm going to accept Nick's answer because it'll be slightly more clear to future visitors with the same question. That's the only reason though, both of you were equally helpful to me.
1

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

2 Comments

Thank you! Very helpful to have the docs about this :)
@icecub no worries - it could be better documented, it's a bit crazy that you have to read through all the examples to find it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.