-1

Forgive the bluntness of the question, but I've noticed really you can use either single or double quotes to begin with, along as you follow the suite throughout.

Someone once told me to use double quotes when echoing, outputting or returning, and single quotes for everything else.

But I'd like to know, is there a solid reason when to only use single quotes, or vice versa and not the other?

Lee
  • 4,187
  • 6
  • 25
  • 71
  • 3
    The main difference is that variables will be interpreted in double quoted strings but not single. I.e. `"$hello"` gives the value of the variable `$hello` whereas `'$hello'` will give the literal string `$hello`. – Jim Aug 14 '14 at 10:32
  • I was writing an answer when the question was closed. Anything in double quotes is parsed by PHP. Anything inside single quotes is not. When writing SQL, it is helpfult to use double quotes because you can then use single quotes inside it. If you need a line break or tab, you put them in double quotes like this: `"\n"` or `"\t"`. When I said "parsed" try this: `echo "this is a $thing that I like.";` where `$thing` has a value. The value will be echoed. I'd have elaborated more. – TecBrat Aug 14 '14 at 10:34

1 Answers1

7

The only difference is that double quoted strings interpret embedded variables and a number of escape sequences, while single quoted strings do not. E.g.:

'This is $a \n string'

This is literally the string "This is $a \n string".

"This is $a \n string"

This is a string containing the value of variable $a and a line break.

Use both as appropriate. If neither escape sequences nor variables are of interest to you, I'd default to single quoted strings; with one exception: if you need single quotes in the string, then double quotes are "cleaner". Compare:

'I don\'t care.'
"I don't care."
deceze
  • 510,633
  • 85
  • 743
  • 889
  • I agree with "I'd default to single quoted strings" Even if I need a line break, I'll start with single quote and put `."\n"` at the end of it. I also prefer concatenation over lots of escapes within the string. – TecBrat Aug 14 '14 at 10:37
  • There is a negligible performance increase using double quotes over single, however this does diminish if you have a lot of variables within it and is specific to the PHP version you're running. I tend to use singles in preference too as I'll often be echoing HTML where arguments should be enclosed with doubles. Consistency is key however. – PeteAUK Aug 14 '14 at 10:46
  • @PeteAUK The performance difference is so minuscule as to be irrelevant. I'd go for *readable* source code first and foremost. – deceze Aug 14 '14 at 10:48
  • 1
    @deceze I'd not say irrelevant as it has fluctuated marginally with different versions of PHP (which means it could again) - admittedly not enough to make a difference :D Legibility and consistency should be the name of the game nine times out of ten. – PeteAUK Aug 14 '14 at 11:08