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

 

Link to comment
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.