PHP: Count Lines of a File and Get the Number of Lines in a Text File

by Yang Yang on April 22, 2009

Share This Article:
Subscribe to Kavoir: blog feed

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
Share This Article:
Subscribe to Kavoir: blog feed

You should also read:

{ 2 comments… read them below or add one }

Randall Ijams July 12, 2009 at 5:09 am

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().

Reply

Yang Yang July 12, 2009 at 1:25 pm

@Randall,

Thanks for your input. That’s some great code. :)

Reply

Leave a Comment

Previous post:

Next post: