Isityou Posted March 6, 2008 Share Posted March 6, 2008 What exactly does wrapping your variable in brackets do? $test = "hello {$name}!"; Link to comment https://forums.phpfreaks.com/topic/94760-variables-wrapped-with-brackets/ Share on other sites More sharing options...
wildteen88 Posted March 6, 2008 Share Posted March 6, 2008 It basically just a pointer for PHP and comes especially useful when using variables which are an associative array within a string, eg: $arr['test'] = 'world'; echo "hello $arr['t']"; The above code will cause the following error: Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /path/to/script.php on line X However if you wrap the variable in braces the code will run fine. $arr['test'] = 'world'; echo "hello {$arr['t']}"; Link to comment https://forums.phpfreaks.com/topic/94760-variables-wrapped-with-brackets/#findComment-485214 Share on other sites More sharing options...
PFMaBiSmAd Posted March 6, 2008 Share Posted March 6, 2008 It helps the parser find the start and end of variable names. For the example you posted, the parser could find the $name variable without error. But for array variables and a case like the following, php needs help figuring out what to do - $test = "hello $name_abc!"; In this example, because the under-score is valid in a variable name, php would not be able to figure out if you mean to echo $name followed by the characters _abc or if you mean a variable called $name_abc Link to comment https://forums.phpfreaks.com/topic/94760-variables-wrapped-with-brackets/#findComment-485216 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.