Home >Backend Development >PHP Tutorial >PHP efficiently counts the number of lines in large files
How to efficiently count the number of lines in large files in php? This article mainly shares examples of ultra-fast and efficient counting of lines in large files in PHP. I hope to be helpful.
Use php to get the number of file lines. The answer given on the Internet is usually to use file to read it all at once, which is not suitable for large files. Usually for large files, we use a while loop to count line by line, which is too slow.
The fastest way is to count multiple lines, read N bytes each time, and then count the number of lines. This is more efficient than Row by row is much more efficient.
Test situation, file size 3.14 GB
1st time: line: 13214810, time:56.2779 s;
2nd time: line: 13214810, time:49.6678 s;
/* * 高效率计算文件行数 * @author axiang */ function count_line($file){ $fp=fopen($file, "r"); $i=0; while(!feof($fp)) { //每次读取2M if($data=fread($fp,1024*1024*2)){ //计算读取到的行数 $num=substr_count($data,"\n"); $i+=$num; } } fclose($fp); return $i; }
Related recommendations:
PHP file reading fread, fgets, fgetc, file_get_contents and Example code for using the file function
The above is the detailed content of PHP efficiently counts the number of lines in large files. For more information, please follow other related articles on the PHP Chinese website!