Jack Maessen Jack Maessen - 1 year ago 125
PHP Question

how to check if value already exists in txt file

I am writing UserID's to a text file seperated with


The var
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:


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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download