A string is nothing more than a series of characters, and it’s one of PHP’s eight primitive types (I’ll cover the remaining ones later on).
Since web pages involve mostly text you’ll be using PHP strings a lot.
Strings in PHP can be represented with either single or double quotation marks. So “Hello World” is pretty much equivalent to ‘Hello World’. There are two main differences, though, explained later on.
Before explaining the differences we need to talk about escape sequences. A escape sequence is a combination of characters to produce another one in special circumstances). For example, let’s say you want to print the follow sentence with a PHP script: “This is Peter’s car.”
If you write your script like this:
echo 'This is Peter's car';
You’ll get an error, because the PHP interpreter will assume that the string finished right after Peter. If you want to make that apostrophe part of the string you need to use the escape sequence \’ (most escape sequences begin with a backslash).
echo 'This is Peter\'s car';
The code above works fine. An alternative is to alternate double with single quotation marks. So:
echo "This is Peter's car";
would also work, as would this:
echo 'The "Lord of the Rings" book is very long.';
Other common escape sequences are \n to add a newline, \t to add a tab and \\ for the backslash itself. In fact from now on I’ll add the \n escape sequence to the end of all strings to make sure we print a newline after them, which makes reading the output easier.
Now this is the first difference between the types of strings: strings with single quotation marks only support the \’ escape sequence, while strings with double quotation marks support all of them.
The second difference is that strings with double quotation marks expand variables inside it. I’ll explain variables below and then return to this point.