Question

I want PHP to echo a string stored in a variable, immediately followed by a set of square brackets containing some other text. This goes into a form that will be sent back to PHP, so PHP needs to be able to interpret the output of this command as an array item.

Here are the methods I've tried:

$var='string';

echo "string[0]"    //works, but only because the variable isn't used

echo "$var[0]";    //PHP tries to treat the string as an array
echo "$var\[0]";    //the slash gets echoed
echo "$var[0\]";    //syntax error

echo "$var"."[0]";   //this is what I'm using now. It's very ugly and I want an alternative

Is there any way to make this work without breaking the string into chunks and concatenating them?

Was it helpful?

Solution 2

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.

OTHER TIPS

Here are the top-two ways I can think of to do this in a single output statement, the one you choose will end up being what fits your personal preference the most (and there are probably others available as well):

printf('%s[0]', $var);

echo $var . '[0]';

Make it explicit where the variable ends with curly brace syntax:

echo "{$var}[0]";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top