Search code examples
phparraysincrement

how to increment variable name by 1 in php


I have an associative array in which i bind a string to a variable. Is there an easy way to increment the variable by 1?

$lang = array(  
    'All Articles' => $t0,
    'Main Articles' => $t1,
    'Archived Articles' => $t2,
    'Search Articles' => $t3,
    'Search for' => $t4,
    'Page' => $t5,
    'from' => $t6,
    // and so on...
);

So i am looking for something like that creates the vars $t0 till $t160 per example.

I tried this but does not work:

$i = 0;
$lang = array(  
    'All Articles' => $t.$i++,
    'Main Articles' => $t.$i++,
    'Archived Articles' => $t.$i++,
    'Search Articles' => $t.$i++,
    'Search for' => $t.$i++,
    'Page' => $t.$i++,
    'from' => $t.$i++,

Where it is used for:

Administrator stores the translated string into a .txt file by filling in a form. A txt file looks like this:

Alle Produkte
Hauptartikel
Archivierte Artikel
// and so on

Then read the content of the text file:

$translationfile = 'data/translations.txt'; 
$lines_translationfile = file($translationfile, FILE_IGNORE_NEW_LINES); // all lines of the translations.txt file into an array
for ($x = 0; $x <= 160; $x++) {
    ${"t".$x} = $lines_translationfile[$x];
}
include 'includes/lang.php'; // the associative array

Now in the page i can easily translate a string with $lang['All Articles']


Solution

  • Just create an array of your keys, then you can use array_combine to combine them directly with the lines from the file:

    $translationfile = 'data/translations.txt'; 
    $lines_translationfile = file($translationfile, FILE_IGNORE_NEW_LINES); // all lines of the translations.txt file into an array
    $keys = array('All Articles','Main Articles','Archived Articles','Search Articles','Search for','Page','from', ...);
    $lang = array_combine($keys, $lines_translationfile);