0

$$I have a bunch fo text files I'd like to eventually explode into arrays, but since the amount of text files is dynamically chosen via user input, I can't just initialize them one-by-one and instead am opting for a for loop.

For the sake of example, three text files I have contain the following (excuse the \n, imagine it's a line break):

file1.txt = 1 \n 2 \n 3

file2.txt = 6 \n 2 \n 7

file3.txt = 9 \n 1 \n 9

The code I attempted:

<?php
    for ($i = 1; $i <= 3; $i++) {
        list($line1[$i], $line2[$i], $line3[$i]) = file("public_html/texts/file".$i.".txt");
?>

This obviously doesn't work, but I'm not sure why. In the end, the result should be:

$line1[1] = 1
$line2[1] = 2
$line3[1] = 3
$line1[2] = 6
$line2[2] = 2
$line3[2] = 7
$line1[3] = 9
$line2[3] = 1
$line3[3] = 9

How do I go about doing this?

edit; fixed typo.

1
  • Your code seems right, the error must be elsewhere not your use of list(). Have you checked the file is correctly read and returned by file() ? Commented Nov 2, 2012 at 8:59

2 Answers 2

2

You have an error in your code, see:

file("public_html/texts/file".&i.".txt");
                              ^-- TYPO HERE
Sign up to request clarification or add additional context in comments.

2 Comments

See my comment to your question above, your error should be elsewhere, you seem to be running php with no error logging, otherwise the above typo would cause a PHP parse error that you would have seen. So first enable php error output so you see the errors in your code.
Thank you for the help, I really appreciate it. I do have error logging, and the error I get in WAMP is that any var I try to echo doesn't exist. When I echo say, $line1[1], it says it is undefined.
1
for($i = 1; $i <= 3; $i++) {

    $lines = file('public_html/texts/file' . $i . '.txt');

    $line1[] = $lines[0];
    $line2[] = $lines[1];
    $line3[] = $lines[2];
}

1 Comment

I'm sorry, I don't really see it here. This takes into consideration only file1.txt and file2.txt, but the amount of text files is user defined and can be any number.

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.