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.)

1
  • @Sean The syntax for variable variables would be "${$arr[0]}". Note the extra $. Commented May 8, 2014 at 1:37

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Side note: this is called complex string parsing (curly syntax).
1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.