How to count the number of lines in a text file using PHP

Hello, I have posted several posts on working with a text file in PHP. Some of those were really helpful to the learners. Like
How to read a particular line from a text file in PHP
Fetching Text Data From a Text File Using PHP
Save HTML Form Data in a (.txt) Text File in PHP
But here in this post, I am going to show you How to count the number of lines in a text file using PHP.

 

Count the number of lines in a text file using PHP

To count the number of lines in a text file in PHP we need to use these below PHP function:

  1. file() function in PHP
  2. count() function in PHP

To get a better Idea you may read this post, this post is very similar to this one How to read a particular line from a text file in PHP You just need to extend a single line.

So let’s create a text file first.

Hello I am from line no 1
Hi I am from line no 2
hello again I am from line no 3
Hey I am from line no 4

Now you need to count the number of lines in this text file. Here we have 4 lines.

Save this file with any filename. Here I am going to save it as mytextfile.txt

PHP program to count the number of lines in a text file :

<?php
$my_text_file = "mytextfile.txt";
$all_lines = file($my_text_file);
$number_of_lines= count($all_lines);
echo $number_of_lines;
?>

This above program will give you the number of lines in a text file.

Special note: The file() function actually returns an array. So here $all_lines variable holds the whole text file as an array. count() function will count the number of elements in the array.

 

Leave a Reply

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