FUDforum
Fast Uncompromising Discussions. FUDforum will get your users talking.

Home » Imported messages » comp.lang.php » When do I use {}?
Show: Today's Messages :: Polls :: Message Navigator
Return to the default flat view Create a new topic Submit Reply
Re: When do I use {}? [message #169557 is a reply to message #169530] Fri, 17 September 2010 19:37 Go to previous messageGo to previous message
Chuck Anderson is currently offline  Chuck Anderson
Messages: 63
Registered: September 2010
Karma:
Member
Jerry Stuckle wrote:
> On 9/16/2010 10:13 PM, bruceaj wrote:
>
>> I have code samples where some variables are wrapped in {} (curly
>> brackets.) My problem is that I can find anything in the documentation
>> when they can be uses.
>>
>> Can someone tell me or point me to some documentation??
>>
>> Thanks...
>>
>> Bruce
>>
>
> You use them when you want to evaluate non-simple variables (i.e. array
> elements) in a double-quoted string, such as:
>
> $a = 'World"; // init variable
> $b = array('Hello', 'World');
>
> echo "Hello $a"; // Works - $a is a simple variable
> echo "Hello {$a}"; // Also works - and may be clearer
>
> echo "Hello $b[1]"; // Does NOT work - $b is an array
> echo "Hello {$b[1]}"; // This one works
> echo "{$b[0]} {$b[1]}"; // Also works
>
>

Actually ....
echo "Hello $b[1]"; // DOES work - $b[1] is not an array

You need them when you want to evaluate *associative* array elements
within a double-quoted string, such as:
$b = array('first' => 'Hello', 'second' => 'World');

Then ...
echo "Hello $b['second']"; // does NOT work - syntax error
echo "Hello {$b['second']}"; // DOES work

And as a side note ...
echo "Hello $b[first]";
.... also works. Constants are not evaluated when within double quoted
strings.
See
http://www.php.net/manual/en/language.types.array.php#language.types.array. foo-bar
(read "More examples ...").

Curly brackets are also required when a valid variable name character
follows a variable within a string.
$a = 'underscore';
echo "I like to use $as" instead of spaces"; // does NOT work
// $as is undefined
echo "I like to use $a's" instead of spaces"; // DOES work
// ' is not a valid variable name character
echo "I like to use {$a}s" instead of spaces"; // DOES work
// {$a} is evaluated separate from the s

--
*****************************
Chuck Anderson • Boulder, CO
http://www.cycletourist.com
Turn Off, Tune Out, Drop In
*****************************
[Message index]
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: OOP, classes and databases
Next Topic: @sessionstart()
Goto Forum:
  

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ]

Current Time: Sat Nov 23 17:14:49 GMT 2024

Total time taken to generate the page: 0.05039 seconds