What is the meaning of { }
(curly braces) in string literals in PHP?

- 143,130
- 81
- 406
- 459

- 2,263
- 2
- 15
- 5
-
Possible duplicate of [Is it wrong to use curly braces after the dollar sign inside strings](https://stackoverflow.com/questions/54857520/is-it-wrong-to-use-curly-braces-after-the-dollar-sign-inside-strings) – Pinke Helga Feb 25 '19 at 22:42
-
3@Quasimodo'sclone That is a totally different question and should not be considered a duplicate. – Douwe de Haan Jan 14 '20 at 11:56
4 Answers
This is the complex (curly) syntax for string interpolation. From the manual:
Complex (curly) syntax
This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.
Any scalar variable, array element or object property with a string representation can be included via this syntax. 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 recognised when the$
immediately follows the{
. Use{\$
to get a literal{$
. Some examples to make it clear:<?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}"; 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()}"; ?>
Often, this syntax is unnecessary. For example, this:
$a = 'abcd';
$out = "$a $a"; // "abcd abcd";
behaves exactly the same as this:
$out = "{$a} {$a}"; // same
So the curly braces are unnecessary. But this:
$out = "$aefgh";
will, depending on your error level, either not work or produce an error because there's no variable named $aefgh
, so you need to do:
$out = "${a}efgh"; // or
$out = "{$a}efgh";

- 143,130
- 81
- 406
- 459

- 616,129
- 168
- 910
- 942
-
49too much anal nitpicking about copy/paste. If it makes it easy to understand/find, then it was a good decision. +1 from me, it was exactly what I was looking for, and I did not find it on the PHP manual - maybe because they call it by the proper name, or whatever. But I did find it here. – Gabriel Magana Feb 01 '12 at 20:41
-
10For literal curlies, double them up, e.g. `$vars='x:3,y:9'; $json="{{$vars}}";`. Thanks to [QiGuang's article](http://articles.qiguang.net/2010/05/31/curly-braces-within-double-quotes-in-php/). – Bob Stein Jul 10 '13 at 15:10
-
-
Interesting use case example is `SimpleXMLElement`: `{}` is used to access the node itself, e.g. `$element[0]->{0}`. Since property "0" cannot exist, this will trigger `__get`/`__set` method. This in essence allows you an alternative to `ArrayAccess` for index access, e.g. http://3v4l.org/1F254. – Gajus Apr 29 '14 at 10:59
-
-
and in the example box, whats the best way to get {fantastic}, aka get the curlies as literals but let the variable parse? – My1 Aug 30 '17 at 07:42
-
3If a content inside literal curly braces contains variables too, then add curly-braces to **every** variable: `$min=1;$max=5; echo ".{{$min},{$max}}"` yields `.{1,5}` (I had troubles knowing where to "double [the curly braces] up" mentionned in @BobStein's comment) – Xenos Jul 04 '18 at 12:55
-
The eleventh example would be more clear with these two additional lines: $name = 'hello'; $hello = 'world'; – CaptureWiz May 04 '21 at 21:56
-
Finally, after searching for an hour I got what I was looking for that how can I **access the customised variable through for loop** `$button = ${'button_'.$i};` **So my code gets optimised.** – Ratnesh Jaiswal Jan 02 '23 at 16:40
-
One more example: to use the return value of a method: `echo "my name is {$this-getName()}"`. – Abdull Jan 06 '23 at 12:17
As for me, curly braces serve as a substitution for concatenation, they are quicker to type and code looks cleaner. Remember to use double quotes (" ") as their content is parsed by PHP, because in single quotes (' ') you'll get the literal name of variable provided:
<?php
$a = '12345';
// This works:
echo "qwe{$a}rty"; // qwe12345rty, using braces
echo "qwe" . $a . "rty"; // qwe12345rty, concatenation used
// Does not work:
echo 'qwe{$a}rty'; // qwe{$a}rty, single quotes are not parsed
echo "qwe$arty"; // qwe, because $a became $arty, which is undefined
?>

- 12,272
- 10
- 61
- 91

- 509
- 4
- 3
-
1*"their content is parsed by PHP"* - This is misleading. You *can't* just put arbitrary PHP expressions inside the curly brace syntax, which is what I read your quote to mean. – Mark Amery Oct 17 '15 at 12:43
-
1IMO, overall, it is not quicker to type with brackets. You have to `SHIFT` key press for the double quotes and for the curly brackets. It would be quicker though if you strictly use double quotes. – deflime Jan 29 '16 at 00:03
-
4
-
-
1anything with single quote assigned to variable is treated as string. – shashikant kuswaha Oct 28 '20 at 07:31
-
Adding to @shashikantkuswaha's comment: if the string has single-quotes around it, you don't "ONLY get the literal name of the variable" [that implies `'{$a}'` would yield string containing one character `a`], you *"get a string containing the exact sequence of characters you typed"*: in this example, a string containing 4 characters `{` `$` `a` `}`. – ToolmakerSteve Dec 03 '20 at 21:12
Example:
$number = 4;
print "You have the {$number}th edition book";
//output: "You have the 4th edition book";
Without curly braces PHP would try to find a variable named $numberth
, that doesn't exist!

- 143,130
- 81
- 406
- 459

- 271
- 3
- 4
I've also found it useful to access object attributes where the attribute names vary by some iterator. For example, I have used the pattern below for a set of time periods: hour, day, month.
$periods=array('hour', 'day', 'month');
foreach ($periods as $period)
{
$this->{'value_'.$period}=1;
}
This same pattern can also be used to access class methods. Just build up the method name in the same manner, using strings and string variables.
You could easily argue to just use an array for the value storage by period. If this application were PHP only, I would agree. I use this pattern when the class attributes map to fields in a database table. While it is possible to store arrays in a database using serialization, it is inefficient, and pointless if the individual fields must be indexed. I often add an array of the field names, keyed by the iterator, for the best of both worlds.
class timevalues
{
// Database table values:
public $value_hour; // maps to values.value_hour
public $value_day; // maps to values.value_day
public $value_month; // maps to values.value_month
public $values=array();
public function __construct()
{
$this->value_hour=0;
$this->value_day=0;
$this->value_month=0;
$this->values=array(
'hour'=>$this->value_hour,
'day'=>$this->value_day,
'month'=>$this->value_month,
);
}
}

- 595
- 1
- 5
- 13
-
1That is a useful technique. Nevertheless, I would rarely use it: IMHO, "efficient" would be to *avoid the need to string concat merely to access values*. Name the object properties the way you want to access them: `public $hour;`. Given `$key='hour';`, can do `$it->$key`. Instead of storing value array per object [costs extra storage], store a *class var* or *public constant* with the mapping between property names and db names: `public const value_names = ['hour'=>'value_hour', ...];`. Given these, its easy to write functions that do any needed access. – ToolmakerSteve Dec 03 '20 at 21:30