What are the differences between using "w" and "a" modes in fopen() for writing to a file in PHP, and when should each be used?

When using fopen() in PHP to write to a file, the "w" mode will open the file for writing and truncate the file to zero length if it already exists. On the other hand, the "a" mode will open the file for writing and place the file pointer at the end of the file if it already exists, allowing you to append content to the existing file. The "w" mode should be used when you want to overwrite the existing file or start writing from the beginning, while the "a" mode should be used when you want to append content to an existing file.

// Example of using "w" mode to write to a file
$file = fopen("example.txt", "w");
fwrite($file, "This will overwrite the existing content in the file.");
fclose($file);

// Example of using "a" mode to append to a file
$file = fopen("example.txt", "a");
fwrite($file, "This will be appended to the existing content in the file.");
fclose($file);