Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

php - Echo some string and multidimensional array element in one line of code

I've been struggling with some weird thing about php for a while.

It seems as if it is unable to display some string and a multidimensional array element using one line of code.

For example we have a simple 3d array:

$ARRAY = array('first' => array(array('Hello, World!')));

Now if I want to display some string and that 3rd level element, I'll have to do something like this:

$a = $ARRAY['first'][0][0];
echo"Some string: $a";

Or this:

echo"Some string: ";
echo($ARRAY['first'][0][0]);

So is there any way to actually do it in just one line of code? Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
echo "Some string: {$ARRAY['first'][0][0]}";

Read more at PHP.Net

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 {$. Some examples to make it clear:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...