PHP Tips

Here we list some tips on PHP.

Difference between single quotes and double quotes in PHP

If you are using special characters, ie: end-of-line '\n' or as in the book, a tab char '\t', then you need to use ". Otherwise it doesn't matter.

Mostly, it's a convenience thing. ' can be easily enclosed in ":

"Tom's wife's father" works just fine. However 'Tom's wife's father' causes problems. There is always the ability to "escape" if you need a literal quote:

"She told me, \"Please don't look at me like that,\" and I didn't any more"

It doesn't work the other way - this fails:
'She told me, "Please don't look at me like that," and I didn't any more"

Essentially, it's all about "parsing" - how can the language interpret what it finds.

The BEST way to enclose string literals is ALWAYS with "" - it's the safest. It forces you to escape: \n\t\r\f (etc) and \" or \\ when you want those characters included.

Also true. Good research there.

That means that the following is handled differently:

$x="Gary";
$string = '$x Yanker' // = $x Yanker
$string2 = "$x Yanker" // = Gary Yanker

 

Single-quoted strings do not interpolate variables. Double-quoted strings interpolate variables and expand the many PHP escape sequences.