如何检查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?

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

Prob a good idea to make sure the file was read successfully before you scan it

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