0

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

1 Answer 1

1

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

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

Comments

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.