PHP Associative Arrays - Single vs Double Quotes - php

Is there any difference between using single and double quotation marks for Associative arrays names in PHP ?
e.g.:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
$age = array('Peter'=>'35', 'Ben'=>'37', 'Joe'=>'43');

Practically no.
There is a slight difference, though. If you use double quotes, the string will be computed; embedded variables will be expanded.
Single quotes on the other side are literals. They are handled as-is.
I could imagine that the double quotes produce a slight overhead due to computing, but I doubt it's significant.
I personally use single quotes for programmatic stuff and double quotes for user-presented text, unless required otherwise.
That's a neat little rule making life easier ;-)

No, apart from the general PHP rules regarding the quotes. See also http://php.net/manual/en/language.types.string.php

No.
Single vs. double quotes in this context only matters if the thing between the quotes is a variable.
For example, if $Test = 43,
$Var["$Test"] = $Var["43"] but $Var['$Test'] = $Var['$Test']

Related

PHP - Why single-quoted variables inside doubles are still parsed

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.

query MySQL with PHP but database column has a $

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.

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!

Single Quotes Instead of Double Quotes?

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

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