4

I would like to know when and why should I use {$var}

echo "This is a test using {$var}";

and when (and why) should I use the simple form $var

echo "This is a test using $var";
hakre
  • 193,403
  • 52
  • 435
  • 836
sica07
  • 4,896
  • 8
  • 35
  • 54

5 Answers5

5

You would use the latter when a) not accessing an object or array for the value, and b) no characters follow the variable name that could possibly be interpreted as part of it.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
5

http://php.net/manual/en/language.variables.variable.php

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
4

The brackets allow you to remove ambiguity for the PHP parser in some special cases. In your case, they are equivalent.

But consider this one:

$foobar = 'hello';
$foo = 'foo';
echo "${$foo . 'bar'}"; // hello

Without the brackets, you will not get the expected result:

echo "$$foo . 'bar'"; // $foo . 'bar'

For clarity purposes, I would however strongly advise against this syntax.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
3

If you write

echo "This is a test using $vars"

You do not get content of $var in result text.

If you write

echo "This is a test using {$var}s";

Everything will be OK.

P.S. It works only with "" but not for ''.

sica07
  • 4,896
  • 8
  • 35
  • 54
degratnik
  • 830
  • 2
  • 9
  • 19
  • If $var ="bla" will output "This is a test using blas", so I think you're wrong. – sica07 May 24 '11 at 14:23
  • @sica07 Here $vars in the first case is not defined, So it will throw an PHP Notice: Undefined variable: vars . But if you have defined it will echo as its in double quotes. The {$var}s make sure that $var is defined , like separating the variable and string that need to be combined. – Hari K T May 24 '11 at 17:58
1

The {} notation is also useful for embedding multi-dimensional arrays in strings.

e.g.

$array[1][2] = "square";

$text = "This $array[1][2] has two dimensions";

will be parsed as

$text = "This " . $array[1] . "[2] has two dimensions";

and you'll end up with the text

This Array[2] has two dimensions

But if you do

$text = "This {$array[1][2]} has two dimensions";

you end up with the expected

This square has two dimensions.
Marc B
  • 356,200
  • 43
  • 426
  • 500