dongsu1539 2016-07-20 22:29
浏览 133
已采纳

如何检查txt文件中是否已存在值

I am writing UserID's to a text file seperated with || The var $UserID is an integer like 1, 2, 3 etc.

If a user has ID 1; the value is stored in the txt file and looks after some time like this:

1||1||1||1||1||...

What i want to achieve: if an ID is already stored in the txt file, do not store it again.

this is what i have sofar;

$UserIdtxt = $UserID."||";


$ID = explode("||", file_get_contents("user_id.txt"));
  foreach($ID as $IDS) {

// here must come the check if the ID already is stored in the txt file
     if($IDS != $UserID) {
     file_put_contents("user_id.txt", $UserIdtxt, FILE_APPEND);

     }
  }

How can i make that check?

  • 写回答

2条回答 默认 最新

  • douwuying4709 2016-07-20 22:36
    关注

    All you need to do is test if the new ID is aleady in the exploded array using in_array()

    $UserIdtxt = $UserID."||";
    
    $all_ids = explode("||", file_get_contents("user_id.txt"));
    
    if ( ! in_array($UserID, $all_ids) ) {
        file_put_contents("user_id.txt", $UserIdtxt, FILE_APPEND);
    }
    

    But this is an awful way of storing this kind of information

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面