【问题标题】:PHP check if item in arrayPHP检查数组中的项目
【发布时间】:2019-01-03 04:01:23
【问题描述】:

我目前正在尝试构建一个通用的 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 完成了这项工作 :)

【问题讨论】:

标签: php file conditional file-exists


【解决方案1】:

在文件已经退出后更改

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


}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        file 返回文件中的行,包括尾随换行符,因此它们不会匹配正在提交的字符串(除非它还包含换行符,显然)。

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-07-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-04-13
          相关资源
          最近更新 更多