Klausos Klausos
Klausos Klausos

Reputation: 16060

Read txt file into two-dimensional array

The file contains 3 columns (tab separated) and 10 rows. How to get [column][row] from the array $lines? Currently this array contains 10 rows.

$handle = @fopen('results.txt', "r");
if ($handle) {
    while (!feof($handle)) {
        $lines[] = fgets($handle, 4096);
    }
    fclose($handle);
}

for($i=0; $i<count($lines); $i++)
{
    echo $lines[$i];
}

Upvotes: 2

Views: 1686

Answers (1)

hek2mgl
hek2mgl

Reputation: 158280

For your special pupose the following snippet will work:

$array = array(
    array(), array(), array()
);
foreach(file('results.txt') as $line) {
    // use trim to remove the end of line sequence
    $record = explode("\t", trim($line));
    $array [0][]= $record[0];
    $array [1][]= $record[1];
    $array [2][]= $record[2];
}

Note that I'm using the function file() which is handy in this situation. It returns an array with all lines of a file.

Upvotes: 2

Related Questions