RE: [PHP] Hashes in strings
| From: | Ford, Mike [LSS] | Date: | Thu, 02 May 2002 09:13:22 +0000 |
| Subject: | RE: [PHP] Hashes in strings | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-95656@lists.php.net to get a copy of this message | ||
> -----Original Message-----
> From: Ferry van Steen [mailto:ferry.van.steen@InfoPart.nl]
> Sent: 02 May 2002 09:42
>
> why do these work:
> $vars = "vars";
> $ar[0] = "arrays";
> $hash['vars'] = "hashes";
> str = "I can use $vars in strings";
> str = "I can use $ar[0] in string";
>
> while this one doesn't:
> str = "I can NOT use $hash['vars'] in strings";
Because the string parser doesn't believe ' is a valid character as part of the
"variable name" following a $. Fortunately, this is catered for by using braces to
delimit your $-specification, thusly:
$str = "I CAN use {$hash['vars']} in strings";
The {} notation can be used to delimit any $ specification, even simple ones in cases where you
might otherwise have ambiguity. For example, this will work (even if ungrammatically!):
echo "Today is the {$date}th of $month."
where this won't:
echo "Today is the $dateth of $month."
I strongly recommend using {} if in any doubt -- it can't do any harm, and may just save you
tearing your hair out looking for that elusive bug!!
Cheers!
Mike
---------------------------------------------------------------------
Mike Ford, Electronic Information Services Adviser,
Learning Support Services, Learning & Information Services,
JG125, James Graham Building, Leeds Metropolitan University,
Beckett Park, LEEDS, LS6 3QS, United Kingdom
Email: m.ford@lmu.ac.uk
Tel: +44 113 283 2600 extn 4730 Fax: +44 113 283 3211