In PHP, how can the structure of loops affect the order of data when saving it to a file?

The structure of loops can affect the order of data when saving it to a file if the data is being appended to the file inside the loop. To maintain the desired order, the data should be stored in a variable during the loop iteration and then written to the file after the loop has completed.

$data = array("Data 1", "Data 2", "Data 3");

// Open the file for writing
$file = fopen("data.txt", "w");

// Loop through the data and store it in a variable
foreach ($data as $d) {
    $content .= $d . "\n";
}

// Write the content to the file
fwrite($file, $content);

// Close the file
fclose($file);