Parse PHP array inside a string

PHP Arrays Strings Parsing Variables

Variable parsing definition from the PHP Manual

When a string is specified in double quotes or with heredoc, variables are parsed within it.

There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort.

The complex syntax can be recognised by the curly braces surrounding the expression.

To embed a variable we can use any of the two syntaxes, ex:

$name = 'John';

// Simple syntax, prints Hello John
echo "Hello $name";

// Complex syntax, prints Hello John
echo "Hello {$name}";

If we do the same experiment with arrays:

$person = [
    'name' => 'John',
    'profession' => 'Programmer',
];

echo "Hello $person['name']";

What do you think will return the previous code?

  • A) Hello John
  • B) Syntax error
  • C) Undefined

The right answer is: B!

It complains about: syntax error, unexpected string content "", expecting "-" or identifier or variable or number.

If you check the Simple syntax: Example #15 of the doc about strings you'll find the cause of the error:

When parsing a PHP variable, if it's an associative array, and we want to access the value of a specific index of it, we write the array index without quotes

If we update the previous code to:

echo "Hello $person[name]";

now it works like a charm!

However, this could look kind of weird if you're used to always access the array keys using quotes. If we want to use the index of the array enclosed in quotes, we need to use the Complex (curly) syntax:

// Works, quoted keys only work using the curly brace syntax
echo "Hello {$person['name']}";

It's curious how things apparently so simply can have some much variations.

References

PHP: Variable parsing - Manual

PHP: Strings - Manual