Jump to content

Variables wrapped with brackets


Isityou

Recommended Posts

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']}";

 

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.