PHP字符串嵌入式数组格式:“$ {arr [0]}”vs“{$ arr [0]}”

In PHP, you can embed an array directly in a (double-quoted) string, but it looks like there are two ways to do it; for example:

$arr[0]="foobar";
echo "${arr[0]}";
echo "{$arr[0]}";

They both seem to work, but what is the difference? Is either better?

(It’s frustratingly difficult to look this up due to Google’s lack of special-character support, but I have seen both formats in use.)

Both work because both are valid. 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 {$.

// 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']}";

According to the PHP documentation on Strings, both "${arr[0]}" and "{$arr[0]}" are shown as valid examples. However, after this, only "{$arr[0]}" syntax is used. So you would assume, that this is the "preferred" syntax.

None of them is "better". They are just the same thing expressed in slight different syntax. Check the manual page about string parsing: http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing. It is a very good documentation page, nothing more to say.