Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP embedding array element inside string with curly braces

Tags:

php

I would like to know what the advantage of using curly braces is in the following context:

$world["foo"] = "Foo World!";
echo "Hello, {$world["foo"]}.\n";

is over the following:

$world["foo"] = "Foo World!";
echo "Hello, $world["foo"].\n";

In particular, how is it that the braces resolve any possible ambiguity in this case (or similar cases)?

like image 873
John Goche Avatar asked Jul 10 '12 19:07

John Goche


2 Answers

Second example will not be parsed. So first is better:)

Anyway, I prefer to use

echo "Hello" . $world["foo"] . ".\n";

Because it is more easy to read to me.

Besides, there is another way:

$world["foo"] = "Foo World!";
echo "Hello, $world[foo].\n";

There no resaons to use one or another. you what you(or your team) like.

like image 66
RiaD Avatar answered Oct 23 '22 02:10

RiaD


See the other answers for the "echo" explanation, but if you're using heredoc, such as the following:

echo <<<EOHTML
<td>{$entity['name']}</td>
EOHTML;

You need the curly braces to properly use the associative array.

like image 29
nwalke Avatar answered Oct 23 '22 02:10

nwalke