views:

195

answers:

3

Very basic, but would like to know the difference/security ramifications etc of using " vs. '.

Can someone provide an example that explains when to use each one?

+8  A: 

There are a lot of subtle differences, you'll want to read the php documentation to get a lot of the details, but the important detail are:

Double quotes are parsed whereas single quotes are literals.

You can use variables inline with double quotes, but not with single quotes.

There are some catches though:

<?php
$beer = 'Heineken';
echo "$beer's taste is great"; // works; "'" is an invalid character for variable names
echo "He drank some $beers";   // won't work; 's' is a valid character for variable names but the variable is "$beer"
echo "He drank some ${beer}s"; // works
echo "He drank some {$beer}s"; // works
?>

Single quotes are slightly faster.

altCognito
they are faster since php does not check the strings for vars
sshow
Right, because they are literals, not parsed strings.
altCognito
it's worth pointing out that although yes, single quotes are faster, the difference is minuscule and shouldn't be overstated.
nickf
actually, looking at the results from http://phpbench.com/ - double quotes seem to (somehow) even perform better. in any case, it's not worth changing any habits over.
nickf
@nickf while correct, if you have large strings of static html for example it's worth using single quotes. it's also a good way to avoid accidental interpretation of variable names when you don't expect it.
marcog
PHP 4 had a huge speed difference in parsing single-quoted vs double-quoted strings. It was something like ten-times faster to concatenate strings and variables than to use embedded variable references in double-quotes. PHP 5 seems to have that bug fixed.
staticsan
+7  A: 

When a string is enclosed in double quotes, then escape sequences such as '\n' and variable identifiers such as $var are interpreted.

See the PHP strings manual for specific details and examples.

marcog
+1  A: 

The biggest one is this. Inside double-quotes, you can include variables, but inside single quotes, the variable name will be literal:

$var1 = "hello";

// this will echo "hello world"
echo "$var1 world";

// this will echo $var1 world
echo '$var1 world';

Using double-quotes becomes extremely useful in a number of situations, expecially when you place {} around the variable names. Here are some examples (certainly others can give you more examples):

// array elements
echo "Element 5 is {$myArray[5]}";
echo "Element 2 subelement 3 is {$myArray[2][3]}";
//
// a dynamic key 
$value = "thing";
$someValue = $myArray["some{$value}"]; // returnd $myArray[something]
OneNerd