How does using fopen() and fgets() in PHP compare to using file() for reading and counting lines in a file?

When reading and counting lines in a file in PHP, using fopen() and fgets() allows for more control over the file handling process compared to using file(). fopen() opens a file pointer, while fgets() reads a line from the file. This method is more efficient for large files as it reads one line at a time, reducing memory usage. On the other hand, file() reads the entire file into an array, which can be memory-intensive for large files.

$file = fopen('example.txt', 'r');
$count = 0;

if ($file) {
    while (($line = fgets($file)) !== false) {
        $count++;
    }
    fclose($file);
    echo "Number of lines in file: " . $count;
} else {
    echo "Error opening file.";
}