Mixing html and php variables inside an echo statement - php

This may be a problem of my trouble with using single and double quotes in one statement. But I have this piece of code:
echo '<form>
<input type="submit" value="$number" onClick="function();">
</form>'
The problem with this is that the submit button says the phrase $number instead of the value of that variable.
So I looked around and found this solution:
echo "<form>
<input type='submit' value='$number' onClick='function();'>
</form>
This outputs the value of $number correctly, but I am used to using single quotes around my echo statements and would like to keep it that way. Why does just switching all single quotes into doubles, and doubles into singles fix the problem? And is there a modification to the first bit of code that would allow me to keep the single quotes on echo, and double quotes on the attributes?

In PHP, double quoted strings are automatically parsed for any variables contained within, but single quoted strings are not. Therefore:
$myVar = 21;
echo "myVar: $myVar"
This outputs the text: myVar: 21
Whereas:
$myVar = 21;
echo 'myVar: $myVar'
This outputs the text: myVar: $myVar
One problem with your code is that in HTML, the values of elements' attributes must be enclosed in double quotes, not single quotes. I know that some browsers will accept this form (or even no quotes at all), but this is not the correct method.
There are various ways of achieving what you wish, correctly.
Method one: Escaping double-quoted strings:
$myVar = 21;
echo "<div id=\"$myVar\"></div>";
While this may be a rather inelegant solution, it will work.
Method two: Using string concatenation with single (or double) quoted strings:
$myVar = 21;
echo '<div id="' . $myVar . '"></div>';
This offers a better solution IMO because you can use function calls or any other PHP code in there if you wish.
WARNING:
Please note that when you aren't certain of the contents of $myVar (i.e. the user enters it in), putting it directly into HTML code is a security vulnerability in the form of cross-site scripting (XSS). Imagine the user enters something like this:
lol"><script>alert('XSS!');</script></div><div id="lol2
This will cause the resulting HTML code to contain the following:
<div id="lol"><script>alert('XSS!');</script></div><div id="lol2"></div>
This is just a benign example, but an attacker could easily use the same technique to steal a user's cookies (to pretend to be logged in as that user). The message here is that when you aren't 100% sure of the contents of a variable, don't insert it into HTML code directly. Instead, call htmlspecialchars($myVar). This would translate to the following:
$myVar = $_POST['whatever'];
echo '<div id="' . htmlspecialchars($myVar) . '"></div>';

In PHP, variables inside double quotes are processed and evaluated, while in single quotes everything is considered as part of the string.
A better explanation here:
http://www.trans4mind.com/personal_development/phpTutorial/quotes.htm
double quote example from the above link:
$something="Oh something";
echo "My answer is $something.<br>";
//result is: My answer is Oh something
single quote example from the above link:
echo 'My answer is $something.<br>';
//result is: My answer is $something.

When you use the single quote, everything inside is taken literally, except single quotes. When using double quotes, anything starting with a dollar sign ($) is assumed to be a variable by PHP. When using variables, I usually like to start the echo with a double quote.

If you want to keep using single quotes, you'll need to use the append operator (a period).
echo '<form>
<input type="submit" value="' . $number . '" onClick="function();">
</form>';

You could just do this and avoid the whole song and dance. I think it is easier to read.
<form>
<input type="submit" value="<?php echo $number; ?>" onClick="myFunction()">
</form>

This outputs same to me
echo '<link rel="apple-touch-icon-precomposed" sizes="57x57" href='. ${base_url_favicon} . '/apple-touch-icon-57x57.png />'."\n";
echo "<link rel='apple-touch-icon-precomposed' sizes='57x57' href='${base_url_favicon}/apple-touch-icon-57x57.png' />\n";

PHP differentiates between single and double quoted strings as being different things. Single quoted strings are literals, you want them output as is. Double quoted strings are to be interpreted (scanned) for any PHP variables and the appropriate replacements made.
This is simply a feature (and a useful one) of the language. I would actually recommend that you get used to using double quotes for strings in all languages. There is no language where it is unacceptable and in staticly typed languages (C, C++, Java, ...) single quotes indicate a character while double quotes indicate a string. That is, String foo = 'my string'; would error in Java as would char * foo = 'my string'; in C or C++. However, char foo = 'a'; is valid, as is String foo = "my string";
Only if you need to eke out the last nanoseconds of performance from PHP might you go through and convert double quoted strings to single quoted strings. In other languages it doesn't matter. Afaik, PHP is the only language that make this string specific double vs. single quotes distinction.

PHP performs what is called variable interpolation on double-quoted strings, which means that the strings are searched for any variables that they might contain, whose values are substituted in the string. If you want to keep the single quotes, you will need to concatenate your strings and variables together like so:
echo '<form>
<input type="submit" value="' . $number . '" onClick="function();">
</form>';
Or, if you want to keep the double quotes, you can escape the double quotes that you want to print:
echo "<form>
<input type=\"submit\" value=\"$number\" onClick=\"function();\">
</form>"

Related

How to Return a Stored Value in Inner text using php

PHP Code:
$name = 'click here';
echo '$name';
Here I am Expecting 'Click here' but my Output is:
$name
The PHP Manual addresses this accurately:
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
To solve the issue, use either one of these solutions:
echo "$name";
echo ''.$name.'';
<?php echo $name; ?>
Either use double quotes around your entire echo statement and escape the quotes in your HTML, or use the concantination operator .
Using double quotes:
"$name";
Using the concantination operator
''.$name.'';
Using double quotes causes PHP to evaluate all variables (replace them with their contents) within the string. However to do this you also have to escape the inner double quotes by making them \" so that PHP doesn't confuse them with the end of the string.
Using the concantination operator you are actually creating 3 different strings, the open tag, the contents of the variable, and the closing tag and then gluing them together using the . to make one complete string which is sent to echo.
Manual reference on strings
http://php.net/manual/en/language.types.string.php
The basics are anything within " (double quotes) is evaluated, anything within ' (single quotes) is not.
So for your code there are a few options
Replace single quotes with double quotes and escape embedded double quotes with \
echo "$name";
You can also replace the embedded double quotes with single quotes (i don't think html minds, not sure about html5)
echo "<a href='http://example.net/some.php' class='menu'>$name</a>";
You could also do a printf, this replace %s = string, with your value $name
printf('%s", $name);

using html and java script tags in php

I am confused about using single and double quotes and back slash while using java script and html tags in php can any one please clarify i googled it but still not clear about it. i am confused for this small thing.i am new to programming
- here is my code
<?php
if(isset($_GET['id'])) {
echo '<div id="d2">';
include "test2.php";
echo '</div>'; }
else
{
echo '<div id="d1">';
include "insert.php";
print "<script type=javascript>"
print "document.getEelementById('alertdiv1').innerHTML='hi' ;"
print "</script>"
echo '</div>';
}
?>
In PHP, you can enclose a string in either single quotes or double quotes. Both are valid:
$var = "this is a string";
$var2 = 'this is also a string';
The main difference is that if your string contains a variable, and you want the variable content to be treated as part of the string, you need to use double quotes:
echo "$var which I made";
will return:
this is a string which I made
When you are manipulating html, css and JavaScript strings, you need to make sure that you don't accidentally close your PHP string. For example:
echo "<h1 class='myheading'>Heading Text</h1>";
Notice how I used double quotes to enclose my string? Because I did that, I was able to use single quotes in the html, without escaping them.
If I'd wanted to use double quotes in my string, I would have had to escape them, like this:
echo "<h1 class=\"myheading\">Heading Text</h1>";
The \ tells PHP that the double quote which immediately follows is to be treated as a literal, and not used to terminate the string.
I can't see any problems relating to quotes in your code.
<script type=javascript> — That is not a valid value of the type attribute (which is optional anyway now). Get rid of the type attribute.
document.getEelementById — Element only has 3 es in it, not 4.
alertdiv1 — There is no element with that id in your code
hi as far as concerned single quotes and double quotes doesnt matters when its a string.but when you use any variable inside
$a = 'hi';
echo '$a' ;
will output
$a
but when you use " "
$a = 'hi';
echo "$a" ;
it will print
hi
Basically, if you're using "" (quotation marks) as your delimiter and you then use a quotation mark as part of the string you must escape it by putting a backslash in front of it.
For example:
$string = "This is my string"; // This is fine as the value of the string doesn't contain any quotation marks (")
$string = "I am including a quote in my string \"To Be Or Not To Be\"."; // This is also fine, as I have escaped the quotation marks inside the string
The same applies if you're using '' (apostrophes) as your delimiter and you then want to use them as part of the string, you must escape them using back slash ().
Hope that helps.
$var = "AAA";
echo 'This costs a lot of $var.'; // This costs a lot of $s.
echo "This costs a lot of $var."; // This costs a lot of AAA.

PHP writing Class and id as single quotes instead of double quotes. Why?

I am getting a lot of errors lately on a Joomla project and have found things like (in class code)...
return "<span class='...
or
echo "<h3 id='...
instead of
return "<span class=\"...
echo "<h3 id=\"...
This includes many times a variable in quotes, but it still finds it's way to my browser with single quotes. Before going through and changing these, I wanted to see what others have to say. My project is at http://dev.thediabetesnetwork.com.
I have looked this up and find a lot of conflicting information, so figured I would revive the discussion for the newest PHP/browser configurations and see if I am overlooking other details.
It's a lot easier to read without all the double quotes inside the string being escaped with \.
If you need to output a variable inside a string expression, double quotes must be used. If you are outputting HTML inside double-quotes, you can either use ' or \" to enclose HTML attributes. The first is preferred because it results in cleaner PHP code.
If you don't want your HTML to use single quotes, then you can just escape all of your quotes, use heredoc syntax, or concatenate your variables into the string like:
echo '<div class="test">' . $var . '</div>';
Browser accept both, thus there is no deeper reason to choose one before the other. From the PHP point-of-view it is slightly more readable with single quotes, because you can wrap strings in double quotes and use variable substition. Compare yourself
"<a href='$url'>Foo</a>"
"Foo"
'Foo'
Another solution is to substitute the content manually, for example
sprintf('Foo', $url);
Or heredoc
echo <<<HTML
Foo
HTML;
I would choose the one, that fits best into the current context (regarding the readability).
Double quote and single quotes have different functionality in php.
You can put a variable or even array into a string with double quotes but not so with single quotes.
Both are acceptable in HTML specification. Indeed even no quotes is if there's not spaces. Most people prefer that I know to have double quotes for the php so you can use variables without breaking up your code and readability because no backslashes.
return "<span class='foo'>$foo</span>";
return "<span class=\"foo\">$foo</span>";
return '<span class="foo">'.$foo.'</span>';
return '<span class=\'foo\'>'.$foo.'</span>';
All work but the first one, to most, is the easiest to read and type.
You can read all about php strings, double quotes, single quotes, heredoc and nowdoc syntax in php's documentation here: http://php.net/manual/en/language.types.string.php
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
Is example Heredoc syntax which allows you to pick your starting and ending delimeters for long multiline strings. Nowdoc is the same as heredoc but like single quotes, you can't put variables into the string.
You don't need to use double quotes if the string doesn't need evaluating (e.g. if it contains variables, etc). In fact, because double quotes causes the string to be evaluated, they're less efficient than using single quotes and concatenating.
Furthermore, it's convention to use double quotes inside HTML tags, so this is how I'd do it:
return '<span class="test">' . $var . '</span>';
In my opinion, Joomla is very poorly coded, and what you've posted is just another example of this.
Another advantage to this method, as you can see above, is that code highlighters and IEDs make it easy to differentiate between "static" strings and variables.

Difference between uses of inverted commas in PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between single quote and double quote string in php
Can you use " and ' interchangeably, 100%? Or is there a reason or use for each? What is the difference exactly?
Observe for yourself:
$name = 'John';
echo "Hello $name" . '<br>';
echo 'Hello $name';
Result:
Hello John // result from double quotes
Hello $name // result from single quotes
As can be seen variables inside double quotes are parsed while in single quotes they aren't.
So when you put variables inside double quotes, they can be parsed and their correct value is output whereas with single quotes, variables are not parsed and you get the same output of variable name itself as in Hello $name.
Since variables inside single quotes aren't parsed, using them is just a little good when it comes to performance.
If there is no question of variables inside quotes, you can use them inter-changeably though keeping above performance tip in mind.
For more information, you can look at the official documentation.
Just to add to the great answer of Sarfraz, there are certain situations where you would want to use one or the other.
Single quotes ('') are always parsed slightly (minutely) faster than double quotes so if you are an optimization freak, a good rule of thumb is to use single quotes instead of double quotes if you will not be parsing any variables.
However, if you have tons of variables and don't want to do something like:
echo 'My name is ' . $name . '!';
then you're better off with double quotes.
However when dealing with html output, you may consider the hassle of escaping your double quotes too tedious to deal with:
echo "<p id=\"myParagraph\">$name</p>";
So in this case the vote goes to single quotes.
Another thing is that when you build SQL queries with PHP, you may notice that you might prefer using double quotes to be able to parse variables and avoid escaping the single quotes:
"SELECT * FROM CoolGuys WHERE Name = '$name'";
In the end it's all a matter of preferrence. :)
Good luck!

learning about single and double quotes (.),("), and (')

Can you tell me what is the different using (')single quotes inside (")quotes and (")quotes inside (')single quotes? and at concat, what is the meaning of this '".$bla."' I still can not distinguish them.
In SQL, anything with single quotes is considered a text based data type.
SQL uses double quotes for escaping keywords and non-ASCII characters.
This:
'". $bla ."'
..is PHP syntax. $bla is a PHP variable, the period is a string concatenation character (which is why there's one on both sides). So in this example, the content of the $bla variable is being concatenated into a string, where it will be surrounded by single quotes.
The main difference is the anything in a double quote is evaluated and anything in a single quote is not. There has been some discussion that it is better to use single quotes than double quotes so that PHP does not need to evaluate every aspect of the line to determine if it is a variable or not:
$good = 'really good';
echo "this is not $good"; //bad
echo 'this is' . $good; //good
It just keeps thing running faster and keeps the code looking cleaner.

Categories