How can PHP be used to check if an entry exists in a text file and output a message if it does or add it if it doesn't?
To check if an entry exists in a text file using PHP, you can read the file line by line and compare each line to the entry you are looking for. If the entry is found, you can output a message indicating its presence. If the entry is not found, you can append it to the end of the file.
<?php
$entry = "example_entry";
$filename = "data.txt";
$found = false;
$file = fopen($filename, "r");
while(!feof($file)) {
$line = trim(fgets($file));
if($line == $entry) {
$found = true;
echo "Entry already exists in the file.";
break;
}
}
fclose($file);
if(!$found) {
$file = fopen($filename, "a");
fwrite($file, $entry . "\n");
fclose($file);
echo "Entry added to the file.";
}
?>
Keywords
Related Questions
- What role does data type conversion play in ensuring accurate comparisons of multidimensional array values in PHP?
- What role does proper data sanitization play in preventing syntax errors in SQL queries when updating database records in PHP, and how can it be implemented effectively?
- What are the best practices for handling variables like $text or $text11 in PHP to avoid errors?