Table of Contents
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.
1 2 3 4 5 6 7 8 |
<?php $lines = file("file.txt"); $num_lines = count($lines); echo $num_lines; |
Output
1 2 3 |
7 |
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.
1 2 3 4 5 6 7 8 |
<?php $str = file_get_contents("file.txt", FILE_IGNORE_NEW_LINES); $num_lines = substr_count($str, "\n"); echo $num_lines; |
Output
1 2 3 |
6 |
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.
1 2 3 4 5 6 7 8 |
<?php $str = file_get_contents("file.txt", FILE_SKIP_EMPTY_LINES); $num_lines = substr_count($str, "\n"); echo $num_lines; |
Output
1 2 3 |
6 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $file = fopen("file.txt", "r"); $num_lines = 0; while (!feof($file)) { $line = fgets($file); $num_lines++; } fclose($file); echo $num_lines; |
Output
1 2 3 |
7 |
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.