Jump to content

What's the Difference?


rick2302

Recommended Posts

When such references are embed in double quoted strings, this ensures the variable is read as it should. It is actually necessary if you want to have two variables printed right next to each other. For example:

echo "$_POST["userName"]";

is the same as

echo "{$_POST["userName"]}";

butecho "$_POST["userName"]$_POST['status']";will result in just

$_POST["userName"]$_POST['status']

being printed out, whereas

echo "{$_POST["userName"]}{$_POST['status']}";

Ensures you have two variables printed out right next to each other.If you see the second form used with just one variable... it's not wrong or anything. It's just there for readability.I'd normally avoid this method though. The variable reference is not highlighted specially in editors, and this often created messy codes for me.

Link to comment
Share on other sites

You really only need it for arrays or classes. If you try to print this:echo "Hello $data['person']['name']";it is ambiguous. You could be asking it to do either one of these:echo "Hello {$data['person']}['name']";echo "Hello {$data['person']['name']}";You need the brackets to tell the interpreter what you mean. It's not technically correct to try and print an array without them:echo "Hello $data['name']";echo "Hello $data[name]";Those may work, but if you have all notices being shown that will produce an error.

Link to comment
Share on other sites

Also, if you are referencing keyed arrays it saves the server having to do a constant check.

echo "My name is {$my['name']}";

is faster than

echo "My name is $my[name]";

It also is useful when variable names followed by more text. So if you had a variable $name followed by "_file", you couldn't type "$name_file" because then the interpreter will look for a variable named $name_file, but if you wrote "{$name}_file" it will understand.Basically, you can think about them as varible delimiters.

Link to comment
Share on other sites

Archived

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

×
×
  • Create New...