2

I'm attempting to access a nested array element within a double quotes string, like this:

"$variable[first_index][second_index]";

This is throwing an Array to string conversion notice and halting my script.

Is there a correct syntax for accessing the data within a string in this manner, or do I need to set a temp variable to reference the required data, and then use THAT in the string?

ineedhelp
  • 227
  • 1
  • 15

1 Answers1

3

Use this syntax:

$string = "Value is {$variable["first_index"]["second_index"]}";

It's called complex extended variable syntax and it's very useful. You can access fields of an object inside string in double quotes, as well as nested array.

Szymon
  • 1,385
  • 1
  • 8
  • 10
  • 2
    @ineedhelp I always go for this approach and recommend that you do. This avoids having bounce between literal strings and variables via concatenation. Your text editor will/should highlight these variables properly which improves readability. After all, double quotes are specifically designed/used in php to permit variables within the string. – mickmackusa Jun 03 '17 at 23:15