Variable… thingy… with {}s

Ask about a PHP problem here.
Post Reply
JelvinJS7
Posts: 341
Joined: Thu May 12, 2011 8:40 pm

Variable… thingy… with {}s

Post by JelvinJS7 »

So I've noticed stuff like this happening in the jacek's videos:
$avariable = "hello";
$notavariable = "world";
echo "{$avariable} {$notavariable}!";
To output "hello world!"

So what I want to know is, what's the deal with the brackets? Cuz can't you output it the same way without them? (as in
$avariable = "hello";
$notavariable = "world";
echo "{$avariable} {$notavariable}!";
)
is it some security measure or something?

AHHHH IT'S SO CONFUSING!!!!
sorry had to spazz out there^


Btw, I already checked the php.net page on variables, and didn't see anything.
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: Variable… thingy… with {}s

Post by jacek »

Without the {} php has to guess which part of the string following the $ indicates the variable. When using {} it tells php exactly which part of the string is the variable.

say you had
echo "I am a test string $variablethat has a variable in it.";
you see how $variablethat could be the variable or $variable
echo "I am a test string {$variable}that has a variable in it.";
Tells php that it is $variable and not $variablethat

In reality though it would not work like this as php stops looking for a variable when it finds a working one, meaning the shortest valid variable is used, but its a nice example ;)
Image
JelvinJS7
Posts: 341
Joined: Thu May 12, 2011 8:40 pm

Re: Variable… thingy… with {}s

Post by JelvinJS7 »

OHHHH! that makes sense!
Duh! (facepalm)
Post Reply