How to store $ in a PHP variable?

I want to save the $ character in a PHP variable.

$var = "pas$wd"; 

I get the following error

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

Reference.

+4
source share
5 answers

You can use single quote strings:

 $var = 'pas$wd'; 

This way the variables will not be interpolated.


Alternatively, you can exit the $ sign with \ :

 $var = "pas\$wd"; 


And, for the sake of completeness, with PHP> = 5.3, you can also use the NOWDOC (single quote) syntax:

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


As a reference, see the PHP Manual Strings page (with a few suggestions):

Note: [...] variables and escape sequences for special characters will not expand when they occur in single quotes.

AND:

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

+13
source

Single quotes prevent expansion:

 var = 'pas$wd'; 
+4
source

Double quotes allow variable interpolation. Therefore, if you use double quotes, you need to exit $ else, you can use a single quote that does not perform variable interpolation.

 $ var = "pas\$wd"; 

or

 $ var = 'pas$wd'; 
+3
source
 $var = 'pas$wd'; $var = "pas\$wd"; 
+2
source
 Use the following code $var='pass$wd' 
+2
source

Source: https://habr.com/ru/post/1305073/


All Articles