[PHP] How to Count Number of Lines in File

In this article, we will explain how to count the number of lines in file using PHP.
We will also discuss methods for counting the lines in all loaded files.



Counting the number of lines in an individual file

By passing a file path to the file function, it returns each line as an array.
You can obtain the number of lines in the file by passing this array to the count function.

function countLines($file) {
    $lines = file($file);
    return count($lines);
} 

echo countLines('./example.php');




Counting the total number of lines in all loaded files

get_included_files function returns the full paths of all included files as an array.
Apply the countLines function (defined earlier) to each file using the array_map function.
Finally, use the array_sum function to obtain the total count of lines across all files.

include('./example.php');

function countLines($file) {
    $lines = file($file);
    return count($lines);
} 

function countLinesAll() {
    $files = get_included_files();
    $lines = array_map('countLines', $files);
    return array_sum($lines);
}

echo countLinesAll();


Additional information about the get_included_files function mentioned above.

This function includes files required with require.
And the file executing this function is also included in the result.








That is all, it was about how to count number of lines in File using PHP.

Sponsored Link

You can subscribe by SNS

Sponcerd Link

Leave a Reply

*