I have text file with some stuff that i would like to put into array. That text file has one value per line. How do i put each line into array?
6 Answers
use the file() function - easy!
$lines=file('file.txt');
If you want to do some processing on each line, it's not much more effort to read it line by line with fgets()...
$lines=array();
$fp=fopen('file.txt', 'r');
while (!feof($fp))
{
$line=fgets($fp);
//process line however you like
$line=trim($line);
//add to array
$lines[]=$line;
}
fclose($fp);
1 Comment
Matthew Flaschen
You can also pass FILE_IGNORE_NEW_LINES as the second parameter to avoid the trailing newline in each array element.
file will return an array of the file content where each element corresponds to one line of the file (with line ending character seqence).
Comments
You can use file().
<?php
$file_arr = file(/path/file);
foreach ($lines as $line_num => $line) {
echo "Line #{$line_num}: " . $line;
}
?>