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

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

2 thoughts on “PHP: Count Lines of a File and Get the Number of Lines in a Text File”

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

Comments are closed.

Scroll to Top