tags:

views:

90

answers:

4

i have an variable

<?php
$a="$testit with $";
ehco $a;

its shows undefined variable $testit but it is not an variable its an string how to do it in php...

+5  A: 

Use single quote,

<?php
$a='$testit with $';
ehco $a;
ZZ Coder
what if I want to create some kind of debug logging: `'$testit value is '.$testit` ? (in other words: is there an escape character?)
xtofl
Backslash is the escape char in double-quoted strings.
ZZ Coder
+14  A: 

There are at least a couple of different solutions -- up to you to choose the one that fits your needs the best ;-)


First, you can use single-quoted strings, like this :

$var = '$testit with $';

This way, variables won't be interpolated.

And (to answser a comment on ZZ coder's answer), if you want to also output the content of a variable, you can use string concatenation :

echo '$testit value is ' . $testit;


Then, another idea would be to use a double-quoted string, and escape the $ sign, with a \ :

$var = "\$testit with \$";

There, you can use \$ to get a $, and use $testit to have string interpolation :

echo "\$testit value is $testit";


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

$var = <<<'STRING'
$testit with $
STRING;

But, with that, you will absolutly not have variable interpolation -- so, you cannot embbed the value of $testit, when using this syntax.


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

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

Pascal MARTIN
+3  A: 

You can also escape the character. No need to escape a dollar without text ajoined.

<?php
$a='\$testit with $';
echo $a;
Glycerine
+2  A: 

From http://www.php.net/manual/en/language.types.string.php, the section on double-quoted strings:

Escaped characters

\$ dollar sign

Victor Nicollet