ZioBit
ZioBit

Reputation: 965

In PHP, how can I add an underscore between two variable names

I have some DB fields called

picture1_en
picture2_en
...
picture1_de
picture2_de
...
picture1_it
picture2_it

Yes, it could have been implemented in another way, but I cannot change the implementation.

Suppose I have a variable called $lang that contains "de" or "en" or "it"
Now, if I want to print the value, I could use this:

for($i=1; $i<=10; ++$i)
  echo $r["picture$i_$lang"];

The problem is that PHP interprets the underscore as part of the variable name (e.g. it interprets it as "$i_"). I tried escaping the underscore in a lot of crazy ways, none of them working.

Sure, I could do

echo $r["picture".$i."_".$lang];

But I was wondering if there is a way to force PHP to interpret the "_" as a string literal, and not as a part of a variable name.

Upvotes: 7

Views: 3013

Answers (1)

Scuzzy
Scuzzy

Reputation: 12332

You can use curly braces to separate the variable name boundaries in a string (double quoted only)

$r["picture{$i}_{$lang}"];

or

$r["picture${i}_${lang}"];

http://php.net/manual/en/language.types.string.php

Complex (curly) syntax

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:

Upvotes: 12

Related Questions