How do we get text from a file (word-by-word) into a 2D array in PHP?

126 views Asked by At

I have a text file with some stuff that I would like to put into a 2D array. That text file comprises of sentences of equal length. How do I put each word into an array?

Example of text file is -

This is stackoverflow

I am user

This file contains 3 words in each line

This - at [0][0] position
is - at [0][1] position
stackoverflow - at [0][2] position

I - at [1][0] position
am - at [1][1] position
user - at [1][2] position

I made something like this but doesn't seem to work out.

$word_count = $word_length = 0;

if ($fh = fopen('array.txt','r')) {
    while (! feof($fh)) {
      if ($s = fgets($fh,1048576)) {
         $words = preg_split('/\s+/',$s,-1,PREG_SPLIT_NO_EMPTY);
         foreach ($words as $word) {
           $word_count++;
           $word_length += strlen($word);

           $array = array();
           for($i=$a;$i<($word_count/4);$i++)    
           {
            for($j=$b;$j<4;$j++)
            { 
             $array[$i][$j]=$words[$j];
            }
           }
                                   }
                                   }
                        }
                                   }

Any help would be appreciated. Thanks

1

There are 1 answers

0
Rizier123 On BEST ANSWER

This should work for you:

Just read your file into an array with file() and explode() each line by a space with array_map().

$lines = array_map(function($v){
    return explode(" ", $v);
}, file("yourTextFile.txt", FILE_IGNORE_NEW_LINES |FILE_SKIP_EMPTY_LINES));