Software Developer

PHP Function to Count Lines in a Data Text File

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;

By

We've 2 Responses

  1. 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:

    function count_lines_in_file($filename) {
      if(!is_file($filename)) return false;
      $fhnd=fopen($filename,"r"); // Open the file
      $c=0; // Declare and initialise the counter
      while(($line=fgets($fhnd))!==false) $c++; // Count the lines
      fclose($fhnd);
      return $c;
    }
    

    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.

    avatar

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]