Reputation: 405
I'm pulling data from a MySQL database and getting the result as an associative array but the fields in the database have space so I have to access the array element with spaces in the key, now that is fine if I just access the element and wrap the key in quotes, but I want to use it in a heredoc and I have a problem accessing the array elements.
An example to show the problem
<?php
$a = array(
'first_element' => 'test1',
'second element' => 'test2'
);
$html = <<<EOF
first element is: $a[first_element]
second element is: $a[second element]
EOF;
?>
the first element can be printed fine since the key doesn't have spaces, the second element can't and resulting in this error
Parse error: syntax error, unexpected string content "", expecting "]" in /Applications/XAMPP/xamppfiles/htdocs/installments/test.php on line 9
if i try to wrap the key in quotes i get another error
Parse error: syntax error, unexpected string content "", expecting "-" or identifier or variable or number in /Applications/XAMPP/xamppfiles/htdocs/installments/test.php on line 9
Upvotes: 0
Views: 457
Reputation:
Use curly brackets and quotes:
<?php
$a = array(
'first_element' => 'test1',
'second element' => 'test2'
);
$html = <<<EOF
first element is: {$a['first_element']}
second element is: {$a['second element']}
EOF;
heredoc syntax, Example #8
Upvotes: 1