Count Lines in File in PHP

To count the number of lines in a file in PHP, you can use one of the following approaches:

Use the file() function

This function reads the entire file into an array, with each line of the file as an element in the array. Then, use the count() function to count the number of elements in the array.

Here is an example of how to count lines in file in PHP using the file() method.

Output

Note that this approach counts empty lines that exist within the file.

This code assumes that you have file.txt in current folder. You can provide relative path or absolute path based on the preference.

Use the file_get_contents() function

Using the FILE_IGNORE_NEW_LINES flag

Here, we can count lines in a file using the file_get_contents() function with the FILE_IGNORE_NEW_LINES flag. This function reads the entire file into a string, ignoring newline characters. Then, use the substr_count() function to count the number of newline characters in the string.

Output

The FILE_IGNORE_NEW_LINES ignores the newlines that are empty, and simply focuses on lines with characters.

Using the FILE_SKIP_EMPTY_LINES flag

Here we make use of the file_get_contents() function alongside the FILE_SKIP_EMPTY_LINES flag to count lines in file.

This function reads the entire file into a string, skipping empty lines. Then, use the substr_count() function to count the number of newline characters in the string.

Here is an example script on how to use the function.

Output

The FILE_SKIP_EMPTY_LINES ignores the newlines that are empty, and simply focuses on lines with characters.

Use the fopen() and fgets() functions

Another approach we can take is count lines in file using a loop. This approach makes use of the fopen() and fgets() function to reads the file line by line, incrementing a counter variable for each line.

Output

Note that this approach counts empty lines that exist within the file.

fopen() method with r is used to open file in read mode.

fgets() method is used to get line from file pointer in PHP.

That’s all about how to count lines in file in PHP.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *