How can the in_array() function in PHP be used to check if an entry already exists in a file before writing a new one?

When writing to a file in PHP, you can use the in_array() function to check if an entry already exists in the file before adding a new one. This can prevent duplicate entries and ensure data integrity. By reading the file into an array, you can then use in_array() to check if the new entry already exists in the array before writing to the file.

// Read the file into an array
$lines = file('data.txt', FILE_IGNORE_NEW_LINES);

// Check if the new entry exists in the array
if (!in_array($newEntry, $lines)) {
    // Append the new entry to the file
    file_put_contents('data.txt', $newEntry . PHP_EOL, FILE_APPEND);
    echo "New entry added successfully!";
} else {
    echo "Entry already exists!";
}