Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an array member inside PHP HEREDOC?

Is there a way to call an array member inside the PHP HEREDOC syntax?

I understand the HEREDOC can take $strings, and that works. I tried calling array members, but that failed:

echo <<<EOF
<tr>
<td>$inner_array_member["ID"]</td>
<td>$inner_array_member["Date"]</td>
<td>$inner_array_member["Time"]</td>
<td>$inner_array_member["Published"]</td>
<td>$inner_array_member["Article"]</td>
<td><a href="rendered.php?editarticle=$inner_array_member["ID"]">EDIT</a></td>
</tr>
EOF;

However, if I rename the strings into simple form ($Article = $inner_array_member["Article"]), and call them, all is fine. Is there any way around this?

like image 997
mrmut Avatar asked Dec 20 '25 02:12

mrmut


1 Answers

Read the manual please before asking a question. It clearly states:

Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.

After checking double-quoted strings, you get a link to string parsing. You take some time to read it, and you find out you have two ways:

echo <<<EOF
<tr>
<td>$inner_array_member[ID]</td>
<td>{$inner_array_member["ID"]}</td>
</tr>
EOF;

I recommend the latter, {$inner_array_member["ID"]}, it is more readable and few people recognize the first form (including me before reading about it last week). First form is also more limited.

like image 166
kapa Avatar answered Dec 22 '25 15:12

kapa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!