john
john

Reputation: 1273

how to create a list of variables in a for loop with php

In a txt file (translations.txt) i have some lines of words which i bind to variables. A txt file looks like this:

All Articles
Main Articles
Previous Page
Next Page
// and so on...

To read the content of all these lines i put them in an array:

$translationfile = 'data/translations.txt'; 
$lines_translationfile = file($translationfile, FILE_IGNORE_NEW_LINES); // all lines of the txt file into an array
// bind content to variables
$translation0 = $lines_translationfile[0] // All Articles
$translation1 = $lines_translationfile[1] // Main Articles
$translation2 = $lines_translationfile[2] // Previous Page
$translation3 = $lines_translationfile[3] // Next Page
// and so on till 40

I try to generate these variables with a for loop:

for ($x = 0; $x <= 40; $x++) {
    $translation.$x = $lines_translationfile[$x]; // Does not work...
}

What is the correct way to generate all these variables till 40 easily?

Upvotes: 1

Views: 246

Answers (1)

I would recommend using array, but if you want to use several variables use the following code.

for ($x=1; $x < 40; $x++) { 
    ${"translation".$x}=$lines_translationfile[$x];    
}

Upvotes: 1

Related Questions