Skip to content
PHP Logo

What is the difference between using 'a+' and 'w' in fopen when working with text files in PHP?

When working with text files in PHP, the main difference between using 'a+' and 'w' in fopen is in how they handle file opening modes. 'a+' opens the file for reading and writing, creating the file if it doesn't exist and positioning the pointer at the end of the file. 'w' opens the file for writing only, truncating the file to zero length if it already exists or creating a new file if it doesn't.

php
// Using 'a+' to open a text file for reading and writing
$file = fopen("example.txt", "a+");

// Using 'w' to open a text file for writing only
$file = fopen("example.txt", "w");