In this article, we will learn how to calculate the number of lines of a file in PHP.


before writing a code let me show you Project structure

Project structure

php-tutorial/
┣ index.php
myfile.txt


myfile.txt is a text file there is some content line by line we will count that lines in PHP


Example

Create an index.php file and put the following code


index.php

<?php


//create function to count line in file
function line_handler($file) {
    
    //open file in "r" mode
    $handle = fopen($file, "r");
    $count = 0;
    
    //get the file nine and count it
    while (fgets($handle)) {
        $count++;
    }
    
    //close the file
    fclose($handle);
    return $count;
}

echo line_handler('myfile.txt');

?>


Before running the project let me show you myfile.txt and see how many lines in it.




Output:

5