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 :)

2
  • $todo is a file object and not an array onbject. in_array suports array as an input in the second parameter Commented Jul 26, 2018 at 8:15
  • Pls check this link stackoverflow.com/questions/9059026/… Commented Jul 26, 2018 at 8:20

4 Answers 4

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);
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

1

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

Comments

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);
}


}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.