Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace part of variable name with value of another variable?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading