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
7Note that this approach counts empty lines that exist within the file.
This code assumes that you have
file.txtin current folder. You can provide relative path or absolute path based on the preference.Use the
file_get_contents()functionUsing the
FILE_IGNORE_NEW_LINESflagHere, we can count lines in a file using the
file_get_contents()function with theFILE_IGNORE_NEW_LINESflag. This function reads the entire file into a string, ignoring newline characters. Then, use thesubstr_count()function to count the number of newline characters in the string.Output
6The
FILE_IGNORE_NEW_LINESignores the newlines that are empty, and simply focuses on lines with characters.Using the
FILE_SKIP_EMPTY_LINESflagHere we make use of the
file_get_contents()function alongside theFILE_SKIP_EMPTY_LINESflag 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
6The
FILE_SKIP_EMPTY_LINESignores the newlines that are empty, and simply focuses on lines with characters.Use the
fopen()andfgets()functionsAnother approach we can take is count lines in file using a loop. This approach makes use of the
fopen()andfgets()function to reads the file line by line, incrementing a counter variable for each line.Output
7Note that this approach counts empty lines that exist within the file.
fopen() method with
ris 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.