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

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]