1

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?

3
  • 2
    Why do you need these variables at all? Just use the array references. Commented Dec 7, 2020 at 20:36
  • The values of these variables may change. I let the user do the translation, and his/her translation phrase will be stored in the translations.txt file. Then i only have to change in the content of the php files, per example the words "Main Articles" with $translation1 Commented Dec 7, 2020 at 20:40
  • That doesn't explain why you need the variables. Where you're using $translation1 you can just as easily use $lines_translationfile[1], although I'd probably use a less cumbersome name for the array. Commented Dec 7, 2020 at 21:03

1 Answer 1

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];    
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.