Single or Double Quotes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
icesolid
Forum Regular
Posts: 502
Joined: Mon May 06, 2002 9:36 pm
Location: Buffalo, NY

Single or Double Quotes

Post by icesolid »

I was just curious. Is there a standard when it comes to single or double quotes?

Like mysql_query("SELECT * FROM table"); OR mysql_query('SELECT * FROM table');

Also when calling things like if and while is there a standard for writing the code like while() { } OR while () { (with space between while and ().

I have seen these situations writen both ways by so many people I just wasnt sure if there was an standard for this.
nowaydown1
Forum Contributor
Posts: 169
Joined: Sun Apr 27, 2008 1:22 am

Re: Single or Double Quotes

Post by nowaydown1 »

It's personal preference really. Double quotes will offer you string interpolation which can make your stuff a little more human readable. (http://us3.php.net/manual/en/language.t ... tax.double). Technically, there is a speed benefit if you don't need interpolation features as in your example above, but you're talking about milliseconds over a couple million iterations. As for your while loop, again personal preference. I generally use while(condition) {.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Single or Double Quotes

Post by Christopher »

It is not really personal preference (other than whether to embed variables or not). Double quotes expand variables in the string; single quotes do not.

Code: Select all

$fields = 'foo,bar';
$table = 'baz';
echo "SELECT $fields FROM $table"   // outputs 'SELECT foo,bar FROM baz'
echo 'SELECT $fields FROM $table';   // outputs 'SELECT $fields FROM $table'
There is no real speed difference though there has been some discussion of that. In general they are used as shown above when either you want or do not want variable expansion. For example. array indexes typically use single quotes (e.g., $foo['bar']). Another reason to use one or the other is when there are quotes in the string and the choice can makes it more readable by not needing slashes (e.g., "That's right!" or '<div id="foo">').
(#10850)
User avatar
puke7
Forum Newbie
Posts: 12
Joined: Sat May 10, 2008 11:49 am

Re: Single or Double Quotes

Post by puke7 »

If you want to get anal with your MySQL syntax table and field names should be wrapped in ticks ` and values in single quotes '.

Somewhere between
"SELECT * FROM `table` WHERE `field` = 'val';"
and
"SELECT * FROM `$table` WHERE `$field` = '$val';"
is what I practice;
Post Reply