Is it more efficient to open a file and read it line by line for processing, rather than loading the entire file into an array?

Opening a file and reading it line by line for processing is generally more efficient than loading the entire file into an array, especially for large files. This approach saves memory as it only loads one line at a time, reducing the overall memory footprint of the script. Additionally, processing the file line by line can be faster as it doesn't require reading the entire file into memory before processing.

$filename = 'example.txt';

if (($handle = fopen($filename, 'r')) !== false) {
    while (($line = fgets($handle)) !== false) {
        // Process each line here
        echo $line;
    }
    fclose($handle);
} else {
    echo 'Error opening the file.';
}