Open In App

How to get the number of lines in a file using PHP?

Improve
Improve
Like Article
Like
Save
Share
Report

Given a file reference, find the number of lines in this file using PHP. There are a total of 3 approaches to solve this.

test.txt: This file is used for testing all the following PHP codes

Geeks
For
Geeks

Approach 1: Load the whole file into memory and then use the count() function to return the number of lines in this file.

Example:

PHP




<?php
    $filePath = "test.txt";
    $lines = count(file($filePath));
    echo $lines;
?>


Output:

3

This approach loads the whole file into memory which can cause a memory overflow issue.

Approach 2: Here we will load only one line of files at a time which is better than the1st approach. PHP fopen() function is used to open a file or URL. The PHP fgets() function is used to return a line from an open file. The fclose() function is used to close the file pointer.

Example:

PHP




<?php
    $filePath="test.txt";
    $linecount = 0;
    $handleFile = fopen($file, "r");
    while(!feof($handleFile)){
      $line = fgets($handleFile);
      $linecount++;
    }
  
    fclose($handleFile);
  
    echo $linecount;
?>


Output:

3

What if 1GB file has only one line in it. This code will load the whole 1GB of data which can cause a memory overflow issue.

Approach 3: We will load only a specific size of data into memory. We don’t care about line breaks at the time of loading. We will iterate on the loaded data to count the number of line breaks in it.

Example:

PHP




<?php
    $filePath="test.txt";
    $linecount = 0;
    $handleFile = fopen($filePath, "r");
  
    while(!feof($handleFile)){
      // We are loading only 4096 bytes of data at a time.
      $line = fgets($handleFile, 4096);
        
      // We are using PHP_EOL (PHP End of Line)
      //to count number of line breaks in currently loaded data.
      $linecount = $linecount + substr_count($line, PHP_EOL);
    }
  
    fclose($handleFile);
  
    echo $linecount;
?>


Output:

3

This is a better approach in terms of space but, note that we are iterating on our data twice So, the time taken will be double.



Last Updated : 22 Jan, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads