Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

php

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.

like image 537
ZioBit Avatar asked Dec 14 '17 04:12

ZioBit


People also ask

Can we use underscore in variable name in PHP?

A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) Variable names are case-sensitive ( $age and $AGE are two different variables)

Can you have underscores in variable names?

Variable names should not start with underscore ( _ ) or dollar sign ( $ ) characters, even though both are allowed. This is in contrast to other coding conventions that state that underscores should be used to prefix all instance variables.

What does the underscore do in PHP?

In PHP, the underscore is generally reserved as an alias of gettext() (for translating strings), so instead it uses a double-underscore. All the functions that make up the library are available as static methods of a class called __ – i.e., a double-underscore.

What is underscore before variable name?

A single leading underscore in front of a variable, a function, or a method name means that these objects are used internally. This is more of a syntax hint to the programmer and is not enforced by the Python interpreter which means that these objects can still be accessed in one way on another from another script.


1 Answers

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:

like image 61
Scuzzy Avatar answered Oct 06 '22 00:10

Scuzzy