PHP Single vs double quotation string
In this chapter you will learn:
Description
Single and double quotation marks work in different ways.
If you enclose a string in single quotation marks, PHP uses the string exactly as typed.
However, double quotation marks has extra features:
- variable names within the string are parsed and replaced with the variable's value
- special characters need escaping in the string
Example
Here are some examples to make these differences clear:
<?PHP//from j av a2 s. c o m
$myString = 'world';
echo "Hello, $myString! \n"; // Displays "Hello, world!"
echo 'Hello, $myString! \n'; // Displays "Hello, $myString!"
echo " Hi\tthere! "; // Displays "Hi there!"
echo ' Hi\tthere! '; // Displays "Hi\tthere!"
?>
The code above generates the following result.
Using double quotes causes the $myString variable name to be substituted with the actual value of $myString.
However, when using single quotes, the text $myString is retained in the string as-is.
With the "Hi there!" example, an escaped tab character (\t
) is
included within the string literal.
When double quotes are used, the \t
is replaced with an actual tab character;
hence the big gap between Hi and there!
in the output.
The same string enclosed in single quotes results in the \t
characters being passed through intact.
Within single-quoted strings, we can use a couple of escape sequences.
Use \'
to include a literal single quote within a string.
To include the literal characters \'
within a single-quoted string, use \\\'
.
Next chapter...
What you will learn in the next chapter: