Home > Software design >  Replace part of variable name with value of another variable?
Replace part of variable name with value of another variable?

Time:05-16

I have one huge translation file which includes all variables starting with the language code like $de_.

$de_anzahl = 'Anzahl';
$en_anzahl = 'Quantity';
$nl_anzahl = 'Aantal';
$tr_anzahl = 'Miktar';
$ru_anzahl = 'Количество';

Usage in 5 different php files looks like the following - for each language only the first two letters change to target the desired language like $nl_

<?php echo $nl_anzahl; ?>

Is it possible to change a part of the variable name by replacing the language part with the value of a variable i extract from the session storage. Something like that:

<?php $nl_language_code = 'nl'; ?>
<?php echo $<?php echo $nl_language_code; ?>_anzahl; ?>

If this is possible i would be able to bulk find and replace the parts and reduce 5 files into one.

CodePudding user response:

No need to <?php ... when you're already inside PHP. You can use this:

<?php

$de_anzahl = 'Anzahl';
$en_anzahl = 'Quantity';
$nl_anzahl = 'Aantal';
$tr_anzahl = 'Miktar';
$ru_anzahl = 'Количество';

$nl_language_code = 'nl';

echo ${$nl_language_code . '_anzahl'};

will output Aantal.

The easier way I think would be to use arrays though

CodePudding user response:

you can also use curly brackets like this:

$de_anzahl = 'Anzahl';
$en_anzahl = 'Quantity';
$nl_anzahl = 'Aantal';
$tr_anzahl = 'Miktar';
$ru_anzahl = 'Количество';

$lang = 'ru_anzahl';
echo ${$lang};
  • Related