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.
Related
Normally, when variables in PHP are enclosed in single quotes, they are treated as strings, i.e
echo '$variable';
will actually echo the word $variable onto the screen.
So why is it then that this string is parsed:
echo "'$variable'";
That code actually does echo the value of the variable. Why is that? It's still inside single quotes, so why does it still get parsed?
The string is wrapped in double quotes -- the single quotes are part of the content of the string, not part of the string's delimiter. Therefore the single quotes have no semantic meaning whatsoever.
Your question indicates that you may have a fundamental misunderstanding of strings. This is OK! Strings are surprisingly complex entities, and will only get more complex if you learn lower level languages like C. I would suggest you spend some time reading up on strings both in general as well as within PHP. A few quick google searches will honestly be better than a curated list for this task.
Because the single quotes are inside double quotes. Anything inside double quotes gets evaluated. So, your echo statement is passed a string inside double quotes.
This string is evaluated then output. It contains single quotes and a variable.
Try this instead:
<?php
$var = 10;
echo '"$var"';
?>
Because it's in double-quotes as well. The outer most layer of quotes denotes what kind of string it is.
It is simply a double quoted string that contains two single quote characters. Once they are in the double quotes, they have no meaning to the parser.
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.
I'm building an application around a database(which was built by someone else, so changing it is not an option). I'm querying the database for values which was working fine until I came across a column in the database that has a $ in it.
The code I'm trying to get to work is...
$avgprice=mysql_result($result1,$i,"avg$cwt");
Try to escape $ sign or use ' instead of ":
$avgprice=mysql_result($result1,$i, "avg\$cwt");
// or imho better way to do it:
$avgprice=mysql_result($result1,$i, 'avg$cwt');
PHP strings:
When a string is specified in double quotes or with heredoc, variables are parsed within it.
and
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.
Use single quotes ' instead of double quotes " to prevent PHP from trying to replace the assumed variable.
$avgprice=mysql_result($result1,$i,'avg$cwt' );
PS: Maybe consider using PDO or mysqli instead of the plain mysql_X functions.
Use single quotes.
$avgprice=mysql_result($result1,$i,'avg$cwt');
Double quotes interpolate (expand) variables. Single quotes do not. Good practice in PHP is to only use double quotes if you want to interpolate variables in the string. Single quoted strings are processed faster because the interpreter doesn't have to look for variables.
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!
Since both are acceptable by HTML as well as languages like ASP.NET and PHP when using attributes or strings, why is it that some people use single quotes and double quotes interchangeably?
It is my understanding that it is syntactically correct to use double quotes where possible, single when you need to embed a double quote for inline logic.
Is there something I am missing?
For examples:
HTML
<a href='http://google.com'>Google</a>
PHP
<? echo 'Hello World!'; ?>
ASP.NET
<form id='myForm' runat='server'></form>
Technically, in PHP single quotes are faster since you don't need to parse the content within.
edit:
So double quotes are automatically converted to single quotes, but if you have variable substitution going on within your double quoted string, that's when you take a performance hit:
http://www.codeforest.net/php-myth-busters-using-single-quotes-on-string-is-faster-then-double-quotes
Either ways, to answer OP's question while the jury is out on this, play it safe (TM) and use single quotes :)
In HTML, I don't think the "why" can be answered in anything but the obvious case: single quoted strings are more convenient when the string contains double quotes, and vice-versa.
In PHP, single quoted strings are more convenient when you don't want any special interpolation or escape characters.
My personal preference is always use double quotes in HTML, and to always use single quotes in PHP unless I need interpolation. Thus, I consider the single quoted strings to be "constants" of sorts in PHP, while the double quoted string implies something else is going on.
<opinion>But why do some people whimsically choose between the two? Probably because they are undisciplined and subsequently not very good programmers.</opinion>
From W3C: http://www.w3.org/TR/html4/intro/sgmltut.html
All attribute values [should] be delimited using either double quotation
marks (ASCII decimal 34) or single quotation marks (ASCII decimal 39).
Single quote marks can be included within the attribute value when the
value is delimited by double quote marks, and vice versa.
Strings in PHP follow the same principle - interchangeable single/double quotes.
I would say that for most people, single and double quotes are treating and used interchangeably without a real understanding of the difference.
Both are used to create/delineate strings.
'Hello'
"Hello"
Both are strings and are treated the same when used in this circumstance.
The difference in in processing. Technically, single quotes strings are not processed when created and stored in to memory. They are taken as is and made into strings.
Double quoted strings are processed when created and stored into memory. That is why you can put a variable into a double quoted string and it's value will be put in, but in a single quoted string the literal variable is put in. For most things, there is not a real difference if you sing a single or double quote except when creating strings with variables, function calls, etc and for saving some milliseconds in processing.
Basically, the choice is yours. But for readability & maintainability, pick one form & stick with it.
I find the use of single quotes advantageous when I'm embedding html into strings, mainly when dealing with templating. Here is an example:
public string EmailTemplate =
#"<div style='color:red'>HEY {0}! BUY MORE STUFF</div>"
// later in code
instanceOfStringBuilder.AppendFormat(EmailTemplate, firstNameVariable);
I don't have any hierarchy in my mind for whether single or double quotes are "better." It is purely a matter of being consistent and having something that programmatically works.
I agree with #stillstanding on the issue of interchangeability within HTML. However, in PHP I use double quotes in instances where I need a variable within a string parsed. Consider this:
<?php
$id = 123;
echo "Your id is $id<br />";
echo 'Your id is $id';
?>
This will output
Your id is 123
Your id is $id