6

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?

1

6 Answers 6

23

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);
Sign up to request clarification or add additional context in comments.

1 Comment

You can also pass FILE_IGNORE_NEW_LINES as the second parameter to avoid the trailing newline in each array element.
1

use file()

https://www.php.net/manual/en/function.file.php

Comments

1
$fileArr = file("yourfile.txt")

http://www.php.net/manual/en/function.file.php

Comments

0

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

0
$lines = file('file.txt');

Documentation

Comments

0

You can use file().

<?php
$file_arr = file(/path/file);
foreach ($lines as $line_num => $line) {
    echo "Line #{$line_num}: " . $line;
}
?>

php.net file()

Comments

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.