Are there any best practices or alternative methods for efficiently counting and summing lines in a text file using PHP?

To efficiently count and sum lines in a text file using PHP, you can read the file line by line and increment a counter for each line read. You can also sum the values of each line if they are numeric.

$file = 'example.txt';
$lineCount = 0;
$sum = 0;

$handle = fopen($file, 'r');
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        $lineCount++;
        $sum += (int)$line; // Assuming each line contains a numeric value
    }

    fclose($handle);
}

echo "Total lines: $lineCount\n";
echo "Sum of values: $sum";