1

I accidentally tested this today, can anyone explain to me why this works and what it is?

$a = array(
array(
'download' => '1500k'   
)
);

echo "Test-{$a[0]['download']}";

Output : Test-1500k

  • 3
    It's [complex (curly) syntax](http://php.net/manual/en/language.types.string.php#language.types.string.parsing.complex). If you use curly braces inside double quotes, PHP will evaluate the entire string inside those braces to a variable and then prints the result of it. It allows you to include more complicated variables like `echo "my first child is {$this->child(0)->firstName}";` – Luke Sep 12 '17 at 05:31

3 Answers3

1

double quotes evaluate the string as a expression and extract variable from it and put their value instead. but single quote show string as is.

if you want more detail you can see this answer in SO.

Navid_pdp11
  • 3,487
  • 3
  • 37
  • 65
0

Your code:

 echo "Test-{$a[0]['download']}";

is the same as:

echo "Test-".$a[0]['download'];

{}\ just wraps array item $a[0]['download'] in string to put its value there

diavolic
  • 722
  • 1
  • 4
  • 5
0

In the context of a double quoted string, variables can simply be inserted by name, but this does not work for inserting array values, so the curly braces are required to let PHP know that the array value as a whole is to be inserted into the string.

In your example, if you remove the curly braces, you will see that it throws an error, and that's because PHP has no way of knowing that the [0]['download'] part is not just a string. It throws an array to string conversion error.

So that's why the curly braces are necessary.

Brian Gottier
  • 4,522
  • 3
  • 21
  • 37