What are the advantages and disadvantages of using file() versus file_get_contents() in PHP for reading text files?
The main advantage of using file() in PHP for reading text files is that it returns an array containing each line of the file, making it easy to iterate over the lines. However, file_get_contents() reads the entire file into a string, which can be more memory efficient for small files. Additionally, file_get_contents() allows for more control over how the file is read and processed.
// Using file() to read a text file
$fileLines = file('example.txt');
foreach ($fileLines as $line) {
echo $line . "<br>";
}
// Using file_get_contents() to read a text file
$fileContents = file_get_contents('example.txt');
echo $fileContents;