I am currently trying to build a generic TO DO app. I have an input field where the user can submit a task and then it's written in a file called 'todo.txt'.
if(isset($_POST["submit"])) {
$task = $_POST["task"];
//check if file already exists
if(file_exists("var/www/html/todo/todo.txt")) {
//read file as array
$todo = file('todo.txt');
//check if task is in array
if(in_array($task, $todo)) {
echo "Task already exists!";
} else {
//add task
file_put_contents('todo.txt', $task.PHP_EOL, FILE_APPEND);
$todo = file('todo.txt');
}
//file not found, create file and and task
} else {
file_put_contents('todo.txt', $task.PHP_EOL, FILE_APPEND);
}
My problem is that the conditional branch where i check if the task is already set and written in file, if(in_array($task, $todo)), does not work, the same task is keep getting added.
Thanks for answers, the flag FILE_IGNORE_NEW_LINES did the job :)
file returns the lines in the file including the trailing line-breaks, so they won't match the string that's being submitted (unless it also contains a line-break, obviously).
The easiest way to avoid this is to use the FILE_IGNORE_NEW_LINES flag:
$todo = file('todo.txt', FILE_IGNORE_NEW_LINES);
My suggestion is to use a json file instead of txt file. that will grant you the full array functionalities without any issue what so ever.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With