As we know, lines are separated from each other by line breaks indicated by “\n” in PHP, therefore, one method would be to explode() the entire file content string by “\n” into an array and then count() the number of the array items to come to the number of lines of that file.
However, there’s already a native built php function able to recognize line breaks, and that is fgets().
So, to count the lines of a file and get the line count:
$lines = 0;
if ($fh = fopen('orders.txt', 'r')) {
while (!feof($fh)) {
if (fgets($fh)) {
$lines++;
}
}
}
echo $lines; // line count
You should also read:
- Simplest PHP Hit Counter or Download Counter – Count the Number of Times of Access (Page Views or File Downloads)
- PHP: Wrap Long Lines | Insert Line Breaks into a Long String
- PHP: Reading a File into a String or Reading the File into an Array
- PHP Array Length Function to Get Length of Arrays
- PHP: Randomizing All Lines of a File – Shuffle Lines in a Text File


Facebook
Twitter
Google Plus
{ 2 comments… read them below or add one }
Firstly, thanks.
Secondly, there is no need for the if (fgets($fh)). In fact if the very last line is blank it will not be counted due to the if. This is also true if you try to use file($sFileName) to read into an array.
So below is what I created and I believe it works.
/*==========================================================
Can not use the following code as it will not count an empty last line.
$asLines = file($sFileName); // $asLines is an array of strings with all the lines from file.
$iLines = count($asLines);
NOR do we need to check what is read.
$sLine = fgets($fh);
if ($sLine) {
$iLines++;
} else { // Check if last line is empty.
if ($sLine == ”) $iLines++;
} // if.
———————————————————-*/
function iLinesInFile($sFileName) {
$iLines = 0;
if ($fh = fopen($sFileName, ‘r’)) {
while (!feof($fh)) {
fgets($fh); // Burn a line so feof will work correctly.
$iLines++; // This will increment even for blank lines and even if the very last line is blank.
} // while.
}// if.
return $iLines;
} // iLinesInFile().
@Randall,
Thanks for your input. That’s some great code. :)