Search code examples
phpfileconditional-statementsfile-exists

PHP check if item in array


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


Solution

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