You can use the curly brace syntax. From the PHP manual documentation on Strings:
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{
.
Surround the expression within curly braces (like so: {$var}
), so PHP knows where the variable begins and ends.
$var = 'foo';
echo "{$var}[0]"; // => foo[0]
This way, you wouldn't have to worry even if the variable was a quoted array index like $var['foo']
either.