Search for duplicates in a local text file

please can someone help me with this duplicate check feature. I'm still pretty fresh when it comes to PHP, so please excuse me if this is a simple fix.

I store a list of email addresses in a file called list.txt. Here is the contents of the file (each on a new line):

bob@foo.com sam@bar.com tracy@foobar.com 

Now I have a function (not working) that should check if the email is in the list:

 function is_unique($email) { $list = file('list.txt'); foreach($list as $item){ if($email == $item){ return false; die(); } } return true; } 

When I call a function in this test with an existing email address, it still returns true:

 if( is_unique(' bob@foo.com ') ) { echo "Email is unique"; } else { echo "Duplicate email"; } // Returns true even though bob@foo.com is in the list 

I appreciate any input.

+6
source share
6 answers

It's nice to use list , but you have to trim() item when repeating through list , as they still have a line:

 if($email == trim($item)) 

Update: As Nick mentioned, the optional FILE_IGNORE_NEW_LINES flag FILE_IGNORE_NEW_LINES drastically reduce execution speed and code:

 function is_unique($email) { $list = file('list.txt',FILE_IGNORE_NEW_LINES); return in_array($email,$list) ? false : true; } 
+7
source

Either remember trim your email address, or the best solution would be to use FILE_IGNORE_NEW_LINES while you use a file function that allows you to use the built-in PHP array search (should be faster). For instance:

 function is_unique($email) { $list = file('list.txt',FILE_IGNORE_NEW_LINES); return !in_array($email,$list); } 
+2
source

What you can do is read the -using fopen- file and read each line separately. Then you just simply check to see if there is a name there. You can also open it, put the whole file in an array (each line = array line) and toss array_unique to filter out doubles.

0
source

You can read the file line by line and compare the contents of this line with a new letter.

Something like that:

 function is_unique($email) { $file = fopen("list.txt", "r") or exit("Unable to open file!"); while(!feof($file)) { if($email == $file){ return false; die(); } fclose($file); } 

Hope this helps.

0
source

for a list of all non-dual letters:

 $list=array_unique(file('list.txt')); 

to check for duplicates:

 $list1=file('list.txt'); $list2=array_unique(file('list.txt')); count($list1)==count($list2); 
0
source

You want to look at the carriage return and the line at the end of each line of the file

 $fp = fopen('emails.txt', 'r'); while (!feof($fp)) { $eml = fgets($fp); if(trim($eml, " \n\r") == $email) { return false; } } return true; 
0
source

All Articles