This is a PHP function that will return the number lines in a text file. Use it to count lines in a data file. See a usage example below.
The function takes one parameter, $file
, the path to the data text file. It will return 0
if the file is not found.
/** * Count lines a data text file */ function isa_count_datafile_lines($file) { set_time_limit(300); ini_set('memory_limit', '-1'); $arr = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); $c = ( false === $arr) ? 0 : count($arr); set_time_limit(30);// restore to default ini_set('memory_limit','128M');// restore to default return $c; }
Usage Example
This example will count the lines in a file called “datafile.txt” which resides in the “/tmp/” directory. It will display the results on the screen.
$file = '/tmp/datafile.txt'; $count = isa_count_datafile_lines($file); echo 'There are ' . number_format($count) . ' lines in ' . $file;
Stephen
September 12th, 2019 at 11:09 am
I would not recommend this approach, as it has to load the entire file into memory in order to count the lines, which is why you need to unset the memory limit. Instead, you should open the file and read each line in turn, incrementing a counter:
This improved version won’t eat memory, doesn’t require you to unset the memory limit on your server, can cope with any length of file and won’t reset your memory limit to a static amount (which may not be the setting on your server).
Finally, if the file doesn’t exist we return false rather than 0, as this is more in keeping with other PHP functions such as fgets() which return false as an error so this can be trapped as a different occurence to reading a zero length file that does exist.
Isabel
September 13th, 2019 at 2:02 pm
Thanks, I agree. I actually do use your way (
fopen()
andfgets()
) in production (as in here).