How to count the number of non blank lines in php?

Member

by lottie , in category: PHP General , a year ago

How to count the number of non blank lines in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , a year ago

@lottie 

To count the number of non-blank lines in PHP, you can use the combination of file reading functions and conditional statements.


Here is an example code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
$filename = "example.txt"; // replace with your file name or path

$nonBlankLineCount = 0; // initialize the counter

$file = fopen($filename, "r"); // open the file in read mode

if ($file) {
    while (($line = fgets($file)) !== false) { // read each line until end of file
        $line = trim($line); // remove leading and trailing whitespace
        
        if (!empty($line)) { // check if the line is not empty
            $nonBlankLineCount++; // increment the counter
        }
    }
    
    fclose($file); // close the file
} else {
    echo "Failed to open the file.";
}

echo "Number of non-blank lines: " . $nonBlankLineCount;


Make sure to replace "example.txt" with the path or name of your own file. The code reads each line, trims any whitespace, and checks if the line is not empty. If a line contains at least one non-whitespace character, the counter is incremented. Finally, the result is printed with an echo statement.