Paulcraey
Paulcraey

Reputation: 391

How can I concatenate a string with a variable and use it as another variable?

I have a variable $language, which can be: "en", "nl", or "fr".I have 3 other variables $menu_en, $menu_fr and $menu_fr.

I have a php page where I want the menu to appear in any of the 3 languages.

I tried this:

echo '$menu_' . $language;

What I want is the result to be the value of $menu_en and not the string $menu_nl.

How can I do this? Can eval() help?

Upvotes: 3

Views: 236

Answers (2)

user2182349
user2182349

Reputation: 9782

You can use variable variables - like so:

$menuVar = 'menu_'.$language;
echo $$menuVar;

Note the double dollar signs.

Ref: http://php.net/manual/en/language.variables.variable.php

Upvotes: 3

Reversal
Reversal

Reputation: 622

How about using an array?

$menu = array("en" => "Hi!", "it" => "Ciao!", "es" => "Hola!");

$language = "en";
echo $menu[$language]; // this will print Hi!
echo $menu["it"]; // will print Ciao!

Some ref on arrays: http://php.net/manual/it/language.types.array.php

Upvotes: 4

Related Questions