• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

[PHP] Reading file to array


Political User
I can read an entire file into an array using file(). Does anyone know how to read the a specified number of lines into an array instead of the entire file?


I'm sorry Hal...
Political User
You could use file_get_contents to get the contents into a string and specifiy the max number of bytes, then use explode to get it into an array

or just get the array with file and and the loop through it x times and copy it to another array

or use fopen and fgets to get one line of the file at a time and loop until x lines
if you just want to read x number of lines then use something like

define('MAX_LINES', 100);
$fp = @fopen("/path/to/file");
$array_lines = array();
for ($i = 0; !feof($fp) && $i < MAX_LINES && $line = fgets($fp, 1024); $i++)
    $array[] = $line;
This should work, I havent really tested it though, but the Code analyser in the Zend Development Environment didnt chuck up anything syntactically wrong with the code
I have a functions somewhere I knocked up that workks line pascals readln funtion, once I tidied up the office I'll dig it out and post it :)

Members online

Latest posts

Latest profile posts

Hello, is there anybody in there? Just nod if you can hear me ...
What a long strange trip it's been. =)

Forum statistics

Latest member