Quotes around PHP strings

Hi everyone,
I have a background in HTML/CSS and I’m just starting to learn PHP. However, I’m a bit confused about the difference between double and single quoted strings in PHP - Is there anyone who could explain it to me in VERY simple terms?
Thank you in advance,

It can be confusing. I don’t think about it too hard, and if a line isn’t working, I’ll often check whether double quotes should be single quotes or vice versa. It’s to do with where PHP is being integrated within the HTML. If your HTML tags are using double quotes, this may cause problems where your PHP is using double quotes. Same goes for single quotes.

What I would do is go from worked examples and develop your own style for how you use the quotes within PHP and HTML. Depending what you use in HTML will determine what you need to use in PHP sometimes.

This may not be the best answer but I hope it helps understanding.

You can use either single or double quotes, but there are some differences.
With double quotes you don’t have to close the quotes to insert a variable.

$string = "You have $number potatoes left." ;

$string = 'You have '.$number.' potatoes left.' ;

Another difference is how you get new lines.

$string = "This is line 1.\n This is line 2.";

$string = 'This is line 1.
This is line 2.';

And of course it reverses which quotes you must escape.

$heading = "<h1 class=\"fancy\">Sam's Website</h1>" ;

$heading = '<h1 class="fancy">Sam\'s Website</h1>' ;

More on that here.


Thanks very much for your help guys. This makes thing a lot clearer.

Anything enclosed in single quotes is a normal string - the only character that can be escaped there is a single quote.

Anything enclosed in double quotes will be parsed for variables and escaped characters that all need to be converted in order to create the string.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.