2

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.

Any idea how can i solve this? Thanks for answers.

Thanks for answers, the flag FILE_IGNORE_NEW_LINES did the job :)

Alex Dani
  • 31
  • 4
  • `$todo` is a `file` object and not an `array` onbject. `in_array` suports array as an input in the second parameter – VinuBibin Jul 26 '18 at 08:15
  • Pls check this link https://stackoverflow.com/questions/9059026/php-check-if-file-contains-a-string – VinuBibin Jul 26 '18 at 08:20

4 Answers4

5

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);
iainn
  • 16,826
  • 9
  • 33
  • 40
2

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.

Lahiru Madusanka
  • 270
  • 2
  • 13
1

Use FILE_IGNORE_NEW_LINES. The array file returns contains a newline character at the end of each value.

marekful
  • 14,986
  • 6
  • 37
  • 59
0

just change after file already exits

  if(file_exists("var/www/html/todo/todo.txt")) {

$todo_txt= file_get_contents("todo.txt");

if ( ! in_array($some_text_came_from_any_where, $todo_txt) ) {
    file_put_contents("$new_text_here",  $todo_txt, FILE_APPEND);
}


}
Rohit Guleria
  • 72
  • 1
  • 12