1

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?

2

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

6 Comments

they are faster since php does not check the strings for vars
Right, because they are literals, not parsed strings.
it's worth pointing out that although yes, single quotes are faster, the difference is minuscule and shouldn't be overstated.
actually, looking at the results from phpbench.com - double quotes seem to (somehow) even perform better. in any case, it's not worth changing any habits over.
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.
|
9

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.

1 Comment

+1 for including info about escape sequences, which no other answer here seems to have.
2

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.