PHP

Difference between single and double quotes in PHP

February 11, 2022

Difference between single and double quotes in PHP

In this article we will learn the difference between single and double quotes in PHP, when we must choose each of the formats.

single and double quotes in PHP cover

What’s up programmer, how are you? Let’s learn more about PHP!

The Single Quotes

According to the documentation this is the simplest way to specify a string by enclosing it in single quotes

In addition, the only characters that will be ‘escaped’ when using the single quote, is the backslash (\) and also the quote itself.

The others will be represented as the letter itself, for example: \n, which should skip a line

See an example:

echo 'Testing simple quotes \' also a slash \\ , test with \n';

This code will return this result:

Testing simple quotes ' also a slash \ , test with \n

Double Quotes

In double quotes the situation changes regarding escaped characters, we can check a list in the documentation itself

But as examples: the \n to skip a line or the \t to a tab in the string, will be interpreted

In addition to of course the backslash and also the single quote itself, which does not need to be escaped in the middle of a string of double quotes

See an example:

echo "Testing simple quotes '' also a slash \\ , test with \n also the \t .";

We will then have the following output:

echo "Testing simple quotes ' also a slash , test with also the .";

See that the characters are actually escaped, and interpreted as functions and not characters

In addition, there is the possibility of interpreted variables, see an example:

$world = 'World';
echo "Hello $world!";

Check out the return:

Hello World!

Interpreted variable technique is not possible on single-quoted strings

And besides, calling methods and properties in the middle of a string, see an example:

echo "Meu nome é {$object->getName()}";

You will need to use curly braces { }, around properties and methods

Conclusion

In this article we learned  the difference between single and double quotes in PHP

Which are actually several, right?

Double quotes prove to be much more versatile, with the interpretation of variables as well as special characters that can be escaped for additional functionality

The single quote can only escape the quote itself and also the backslash

Want to learn more about PHP? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x