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
This should work for you:
Just read your file into an array with
file()
andexplode()
each line by a space witharray_map()
.