48

I don't know how to explain this but in simple terms I have seen people using {$variable} when outputting values. I have noticed that {$variable} doesn't work everything. When should we use {$variable}?

Red Virus
  • 1,633
  • 3
  • 25
  • 34
  • 2
    That's not vanilla php, that might be php framework syntax, for example blade template engine from Laravel 5 uses `{{$variable}}` to print stuff. – Asur Feb 24 '16 at 09:33
  • 12
    @asur that is incorrect. This is known as [complex (curly) syntax](http://php.net/manual/en/language.types.string.php#language.types.string.parsing.complex). – Francesco de Guytenaere Feb 24 '16 at 09:38
  • 2
    Possible duplicate of [What does ${ } mean in PHP syntax?](http://stackoverflow.com/questions/5571624/what-does-mean-in-php-syntax) – Francesco de Guytenaere Feb 24 '16 at 09:39
  • 2
    @Ciccio Indeed but I think he means curly braces by their own not inside a print – Asur Feb 24 '16 at 09:42
  • What about `"$var['key']"`? Seems to work without curly braces but what is the recommendation? – user9645 Aug 19 '21 at 10:48

3 Answers3

93

What are PHP curly braces:

You know that a string can be specified in four different ways. Two of these ways are – double quote("") and heredoc syntax. You can define a variable in those 2 types of strings and PHP interpreter will parse or interpret that variable too, within the strings.

Now, there are two ways you can define a variable in a string – simple syntax which is the most used method of defining variables inside a string and complex syntax which uses curly braces to define variables.

Curly braces syntax:

To use a variable with curly braces is very easy. Just wrap the variable with { and } like:

{$variable_name}

Note: There must not be any gap between { and $. Else, PHP interpreter won't consider the string after $ as a variable.

Curly braces example:

<?php
$lang = "PHP";
echo "You are learning to use curly braces in {$lang}.";
?>

Output:

You are learning to use curly braces in PHP.

When to use curly braces:

When you are defining a variable inside a string, PHP might mix up the variable with other characters if using simple syntax to define a variable and this will produce an error. See the example below:

<?php
$var = "way";
echo "Two $vars to defining variable in a string.";
?>

Output:

Notice: Undefined variable: vars …

In the above example, PHP's interpreter considers $vars a variable, but, the variable is $var. To separate a variable name and the other characters inside a string, you can use curly braces. Now, see the above example using curly braces-

<?php
$var = "way";
echo "Two {$var}s to define a variable in a string.";
?>

Output:

Two ways to define a variable in a string.

Source: http://schoolsofweb.com/php-curly-braces-how-and-when-to-use-it/

TecBrat
  • 3,643
  • 3
  • 28
  • 45
Fakhruddin Ujjainwala
  • 2,493
  • 17
  • 26
  • 9
    It's also useful for class properties and methods. `"this is a {$class->prop}" and it is {class->method()}"`; https://stackoverflow.com/questions/10002652/in-php-how-to-call-function-in-string – dlaub3 Oct 13 '18 at 15:33
  • 1
    This was helpful. I also strongly agree with @dlaub3 that $class->prop (even without curly braces!) is almost always more effective than {$var}, at least in my experience. – Daniel Mar 02 '20 at 04:28
21

A couple of years late but may I add:

You can even use variable in curly braces to access methods of an Object from a Class dynamically.

Example:

$username_method = 'username';
$realname_method = 'realname';

$username = $user->{$username_method}; // $user->username;
$name = $user->{$realname_method}; // $user->realname

Not a good example but to demonstrate the functionality.

Another Example as per @kapreski's request in the comments.

/**Lets say you need to get some details about the user and store in an 
array for whatever reason.  
Make an array of what properties you need to insert. 
The following would make sense if the properties was massive. Assume it is
**/

$user = $this->getUser(); //Fetching User object

$userProp = array('uid','username','realname','address','email','age');

$userDetails = array();

foreach($userProp as $key => $property) {
    $userDetails[] =  $user->{$property};       
}

print_r($userDetails);

Once the loop completes you will see records fetched from user object in your $userDetails array.

Tested on php 5.6

Viktor Borítás
  • 135
  • 2
  • 11
Sanjok Gurung
  • 948
  • 4
  • 17
  • 33
  • 1
    IMO this is actually the main use case for surrounding the variable with curly braces. That is for using content of a variable to refer to an object property. – Tuhin Paul Jun 16 '18 at 07:38
  • can you add a more detailed example or link to an article with some real world example, thanks.. – kapreski Sep 14 '18 at 00:43
  • @karpreski. I added a new example. Hopefully it has become a little bit more clearer :) – Sanjok Gurung Sep 14 '18 at 09:50
  • 1
    Looks like `$username = $user->$username_method;` produces the same output whether I use curly braces or not. Am I missing something? – LobsterBaz May 11 '21 at 22:25
3

As far as I know, you can use for variable $x

echo "this is my variable value : $x dollars";

… but if you don't have any spaces between the variable and the text around it, you should use {}. For example:

echo "this is my variable:{$x}dollars";

because if you wrote it $xdollars it will interpret it as another variable.

msg
  • 7,863
  • 3
  • 14
  • 33
  • Is there a difference between `echo "this is my variable:{$x}dollars";` and `echo "this is my variable:" . $x . "dollars";` apart from the syntax? – LobsterBaz May 11 '21 at 22:23
  • Technically one is string-concatenation (concatenating strings with (a) dot(s)) where the other is a format string. There would be also `echo "this is my variable:", $x, "dollars";`-way, which is probably fastest, but keep in mind that this `,`-syntax separates actual function arguments towards echo(), hence is specific to echo(). – daten Feb 09 '22 at 23:07
  • I can't edit above comment anymore, but the statement that the `,`'s in above echo-example separate arguments to the function `echo()` doesn't seem to be correct. `echo("foo", "bar");` is invalid. Makes above example (`echo "this is my variable:", $x, "dollars";-`) even more `echo`-specific. – daten Feb 09 '22 at 23:14