How can using a loop improve the efficiency of writing multiple variables to a file in PHP?

When writing multiple variables to a file in PHP, manually writing each variable can be time-consuming and error-prone. Using a loop can improve efficiency by automating the process and reducing the chances of mistakes. By iterating over an array of variables and writing them to the file within the loop, you can streamline the code and make it easier to maintain.

// Array of variables to write to the file
$variables = ['var1', 'var2', 'var3'];

// Open the file in write mode
$file = fopen('output.txt', 'w');

// Loop through the array of variables and write them to the file
foreach ($variables as $variable) {
    fwrite($file, $variable . PHP_EOL);
}

// Close the file
fclose($file);