Bruce
Bruce

Reputation: 35275

How to store $ in a PHP variable?

I want to store a $ character in a PHP variable.

$var = "pas$wd";

I get the following error

Notice: Undefined variable: wd in C:\xxxxx  on line x

Help.

Upvotes: 4

Views: 1063

Answers (5)

muruga
muruga

Reputation: 2122

Use the following code 
$var='pass$wd'

Upvotes: 2

Pascal MARTIN
Pascal MARTIN

Reputation: 401032

You can use single-quoted strings :

$var = 'pas$wd';

This way, variables won't be interpolated.


Else, you can escape the $ sign, with a \ :

$var = "pas\$wd";


And, for the sake of completness, with PHP >= 5.3, you could also use the NOWDOC (single-quoted) syntax :

$var = <<<'STRING'
pas$wd
STRING;


As a reference, see the Strings page of the PHP manual (quoting a couple of sentences) :

Note: [...] variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

And :

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:
\$ : dollar sign

Upvotes: 13

kpower
kpower

Reputation: 3891

$var = 'pas$wd';
$var = "pas\$wd";

Upvotes: 2

codaddict
codaddict

Reputation: 455132

Double quotes enable variable interpolation. So if you are using double quotes, you need to escape the $ else you can use single quote which do not do variable interpolation.

$ var = "pas\$wd";

or

$ var = 'pas$wd';

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798764

Single quotes inhibit expansion:

var = 'pas$wd';

Upvotes: 4

Related Questions