How can one properly clear the contents of a text file in PHP before writing a new array to it, and is using ftruncate() the best approach for this task?

To properly clear the contents of a text file in PHP before writing a new array to it, you can use the combination of fopen() with 'w' mode (to truncate the file) and fwrite() to write the new array data. While ftruncate() can also be used to truncate the file, it may not be the best approach as it requires an open file handle, which can be more cumbersome to manage.

// Open the file in 'w' mode to clear its contents
$file = fopen('example.txt', 'w');
fclose($file);

// Write new array data to the file
$data = ['apple', 'banana', 'cherry'];
file_put_contents('example.txt', implode(PHP_EOL, $data));