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


how to check if value already exists in txt file

我正在将UserID写入一个用||分隔的文本文件变量$UserID是一个像1、2、3等的整数。

如果用户具有ID 1;该值存储在txt文件中,并在一段时间后如下所示:

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

我想要实现的目标:如果一个ID已经存储在txt文件中,请不要再存储它。

这就是我的沙发;

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

我该怎么做那张支票?

您所需要做的就是使用in_array() 测试新ID是否在分解的阵列中可用

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

但这是一种糟糕的存储这种信息的方式

在扫描文件之前,最好确保文件已成功读取

if($source = file_get_contents("user_id.txt"){
    if(!preg_match("/^($UserID|.*'|'|$UserID)/", $source){
        ... //add id to file
    }
}else{/*Todo: handle file-open failure*/}