DEV Community

Farhan Halai
Farhan Halai

Posted on • Updated on

Single vs Double quote strings in PHP

In PHP, string written in single quotes is displayed 'as it is'. Variables and most of escape sequences are not interpolated.

Example,

$name = 'Farhan';
echo 'Welcome $name';
// Output: 'Welcome $name';
Enter fullscreen mode Exit fullscreen mode

Whereas in double quotes, variables and escape sequences are interpolated.

$name = 'Farhan';
echo "Welcome $name";
// Output: "Welcome Farhan"
Enter fullscreen mode Exit fullscreen mode

Edit #1:
Thanks @cseder for correcting to use interpolated instead of interpreted.

Discussion (2)

Collapse
cseder profile image
Chris Sederqvist

To be a nitpicker, the word to use is interpolated / interpolation, as in:
You can use interpolation to interpolate (insert) a variable within a string. Interpolation works in double quoted strings and the heredoc syntax.

Everything in PHP gets interpreted...

For completeness, PHP also has the complex / curly bracket syntax for embedding expressions (yielding a return value) in a string.

Any scalar variable, array element or object property with a string representation can be included.
Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }.

Since { can not be escaped, this syntax will only be recognized when the
$ immediately follows the {.


<?php
// Show all errors
error_reporting(E_ALL);

$great = 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";

// Works
echo "This square is {$square->width}00 centimeters broad.";


// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";


// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong  outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}";

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " . $arr['foo'][3];

echo "This works too: {$obj->values[3]->name}";

echo "This is the value of the var named $name: {${$name}}";

echo "This is the value of the var named by the return value of getName(): {${getName()}}";

echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";

// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>

Enter fullscreen mode Exit fullscreen mode
Collapse
farhanhalai profile image
Farhan Halai Author

Thanks @cseder for correcting me out.
And adding some valuable examples too ✌