To assign string values in PHP, we use quotes. And we use single quotes and double quotes interchangeably as similar things until you get some error.
You’ll feel you’ve written the correct code after checking it multiple times and don’t know why it’s not working.
It’s frustrating, I know and have been there as well.
When are Single Quotes and Double Quotes used in PHP?
Simply, as told earlier quotes are used to assign string variables in PHP.
And if the string value has double quote (“”) on it, then single quotes is used to assign it to the variable.
For example
$variable1 = ‘This is a “GAME” changer’;
// Output: This is a GAME changer.
Similarly, if the string value has a single quote (‘’) on it, then double quotes is used to assign it to the variable.
For example
$variable2 = “I’m Vijay.”;
// Output: I’m Vijay
Escaping
If you don’t want to switch between Quotes (Single and Double), you can simply use escaping technique. Simply, escaping is ignoring a character and you can do it using backslash \ .
For example
$sentence = ‘I\’m Vijay.’;
// Output: I’m Vijay.
// It simply ignores the single quote after I in the sentence.
And here comes String Interpolation
Apart from generic uses of quotes in PHP, there’s a technique called String Interpolation where you can embed variable values on string which makes it easier to make dynamic texts.
And it can be easily performed with double quotes in PHP.
For example
$name = “Vijay”;
$sentence = “My name is $name”;
// Output: My name is Vijay
Sometimes we forget and use single quotes while passing the variable which gives us an error with a headache as it’s a silly mistake and hard to spot.
For example
$name = “Vijay”;
$sentence = ‘My name is $name’;
// Output: My name is $name
You can also perform string interpolation with single quotes using Concatenation technique. It is a technique of connecting two or more strings/variables. And it’s done with “.” (dot or fullstop) sign in PHP.
For example
$name = ‘Vijay Thapa’;
$sentence = ‘My name is ’.$name;
// Output: My name is Vijay Thapa
So, the difference between single quote and double quote in PHP is subtle but important.
You May Also Like: "Why does the PHP header redirect not work sometimes?"


Comments