Forum Moderators: open
$test = 'hello';
echo "$test"; // will echo hello
echo '$test'; // will echo $test
in Javascript,
var test = 'hello';
alert(test); // will alert hello
alert('test'); // will alert test
alert("test"); // will alert test
To include variables in strings, you must concatenate, with the + being the equivalent of PHP/Perl's . (dot) concatenation operator.
alert('The variable test is ' + test);
alert("The variable test is " + test);
When to use which is a matter of style, but it helps to reduce "toothpick syndrome" so you don't have to escape as much.
alert('Johnny\'s car ain\'t too fast, shouldn\'t it be faster?'); // can make more difficult to debug
alert("Johnny's car ain't too fast, shouldn't it be faster?");
When putting Javascript in PHP, beware of similar language escapes, particularly newlines, \n. These are the same in both languages. But if you do
echo "alert('Here we go \n');"; }
Your newlines will be escaped by PHP and your actual output will be
alert('Here we go
');
\n doesn't interpolate in PHP with single quotes, but the PHP statement is in double quotes, so the nested single-quote Javascript alert is just another character, allowing the \n to be interpolated by PHP. Confused yet? :-)
To maintain newlines in Javascript when generating it from PHP, escape the escape. :-)
echo "alert('Here we go \\n');"; }
[edited by: rocknbil at 6:35 pm (utc) on Nov. 4, 2009]
var html = '<a href="#link"><img src="path" alt="alt" /></a>';
is less typing and cleaner than:
var html = "<a href=\"#link\"><img src=\"path\" alt=\"alt\" /></a>";