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

By Shahnail Khan Last updated : January 10, 2024

Problem statement

Write a PHP script to count the number of lines in a file.

Note: Store a text file name into a variable and count the number of lines of text it has.

Prerequisites

To better understand this solution, you should have basic knowledge of the following PHP topics:

Counting the number of lines in a file using PHP

To count the number of lines in a file, use the file_exists() to check if the file exists, Then by using the file() function, read the content of the file in an array and use the count() function to get the total number of lines. The count() function is to count the number of elements in an array or the number of properties in an object.

file_exists() function

Syntax of file_exists() function is:

file_exists($filename)

Return Value: It returns true if the file or directory exists; false, otherwise.

count() function

The syntax of the count() function is:

count (array, mode)

Here, array: The array or countable object for which you want to count elements. And, mode (optional): An optional parameter specifying the mode of the count.

Return Value: The count() function returns the number of elements in the array or countable object.

PHP program to count the number of lines in a file

In this example, we are getting a printing the count of the number of lines in a file using PHP:

<?php
// Storing the file name in a variable
$fileName = "first.php";

if (file_exists($fileName)) {
    $lines = file($fileName);
    // Count the number of lines
    $numberOfLines = count($lines);
    echo "The file '$fileName' has $numberOfLines lines.";
} else {
    // Output an error message if the file doesn't exist
    echo "The file '$fileName' does not exist.";
}
?>

Output

The expected output of the given code is:

The file 'first.php' has 13 lines.

Code explanation

In my system, I have saved the file name as first.php. You can save your file with another name.

  • First, we create a variable named $fileName and assign the value 'first.php' to it. This is the name of the file we want to check.
  • The file_exists() function is then used to check whether the file specified by $fileName exists. If the file exists, the code inside the curly braces {} will be executed.
  • The file() function reads the contents of the file specified by $fileName into an array called $lines
  • The count() function is used to find the number of elements (lines in this case) in the array $lines, and the result is stored in the variable $numberOfLines.
  • Finally, the code displays the number of lines in the file in the browser.

Note: If the file does not exist, the code inside the else block will be executed, displaying an error message as "The file 'first.php' does not exist".

Counting lines in a text file by reading content line by line

This is another approach to count the lines in a file. Take a variable to store the number of lines, open the file in read mode, read its data (till the end of the file) line by line by using the fgets() function, and increase the counter's value by 1. After this process, close the file and print the counter variable's value.

So, here is the file (file1.txt) that we are using in the below code.

Hello, world!
How're you?
Welcome at IncludeHelp
Let's learn PHP programming with us.

PHP Code

Here, we have a file named "file1.txt" which has 4 lines.

<?php
// file name
$file_name = "file1.txt";

try {
    $line_counter = 0;

    // Open file
    $file_obj = fopen($file_name, "r");

    // check file is opened or not
    if ($file_obj === false) {
        // throw error, if file is not opened
        throw new Exception("Failed. File is not opened.");
    }

    // read file's content line by line
    while (!feof($file_obj)) {
        $str = fgets($file_obj);
        if ($str !== false) {
            // increase line counter
            $line_counter++;
        }
    }

    // close the file
    fclose($file_obj);

    // print number of lines
    echo "Total number of lines: " . $line_counter;
} catch (Exception $e) {
    echo "Execution failed due to this error:" . $e->getMessage();
}
?>

Output

The output of the given code is:

Total number of lines: 4

More PHP File Handling Programs »

All PHP Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.