Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 829
Alex Dani Avatar asked Feb 13 '26 03:02

Alex Dani


2 Answers

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);
like image 163
iainn Avatar answered Feb 15 '26 17:02

iainn


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.

like image 21
Lahiru Madhusanka Avatar answered Feb 15 '26 15:02

Lahiru Madhusanka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!