Saturday, 20 May 2017

php - Why is there an error message if the variable is encased in double quotes?





Look at the code below



//The array is storing a blog entry in it
$entry = array ('title' => 'sample title',
'date' => 'August 9, 2011',
'author' => 'daNullSet',
'body' => 'I shall become a web developer IA',);
echo "The title of the blog is ".$entry['title']."
";
?>



The code above executes quite well, but it returns the following parse error when I enclose $entry['title'] in double quotes while concatenating with other strings in echo statement.




Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\xampp\htdocs\php-ex\test.php on line 7




Can you guide about the reason of the error? I am absolutely new to programming. Thank you


Answer




In order to use a value from an associative array in a string, you need to use the "complex (curly) syntax". What this means, in effect, is that you need to wrap it in {}, like this:



echo "The title of the blog is {$entry['title']}
";


If you try and use a "complex" variable directly in a double-quoted string without using the braces, you will get the parse error you report.



It would be well worth your reading this entire page thoroughly so you know what is and isn't allowed.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...