How can PHP code be optimized to prevent duplicate entries when saving searched words in a text document?

To prevent duplicate entries when saving searched words in a text document, you can first check if the word already exists in the document before saving it. This can be done by reading the contents of the document, checking if the word is already present, and only saving the word if it is not found. Additionally, you can use an array to keep track of the words that have already been saved to avoid duplicates.

// Read the contents of the text document
$contents = file_get_contents('searched_words.txt');

// Split the contents into an array of words
$existing_words = explode(' ', $contents);

// Check if the searched word already exists
$searched_word = 'example';
if (!in_array($searched_word, $existing_words)) {
    // Save the searched word to the text document
    file_put_contents('searched_words.txt', $searched_word . ' ', FILE_APPEND);
}