PHP 检查数组中的项目

PHP check if item in array

我目前正在尝试构建一个通用的 TO DO 应用程序。我有一个输入字段,用户可以在其中提交任务,然后将其写入名为 '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);
}

我的问题是我检查任务是否已经设置并写入文件的条件分支,if(in_array($task, $todo)), 不工作, 相同的任务不断被添加。

知道如何解决这个问题吗?感谢您的回答。

感谢您的回答,标志 FILE_IGNORE_NEW_LINES 完成了工作:)

file returns 文件中的行包括结尾的换行符,因此它们不会匹配正在提交的字符串(除非它也包含换行符,显然) .

避免这种情况的最简单方法是使用 FILE_IGNORE_NEW_LINES 标志:

$todo = file('todo.txt', FILE_IGNORE_NEW_LINES);

使用FILE_IGNORE_NEW_LINES。数组文件 returns 在每个值的末尾包含一个换行符。

我的建议是使用 json 文件而不是 txt 文件。这将为您提供完整的阵列功能,而不会出现任何问题。

文件已经存在后才更改

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


}