Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for duplicate in local text file

Tags:

php

please could someone help me with this duplicate checking function. I'm still quite fresh when it comes to PHP, so please excuse me, if this is a simple fix.

I'm storing a list of email addresses to a file called list.txt. Here is the content of the file (each on a new line):

[email protected]
[email protected]
[email protected]

Now I have a function (not working) that should check if email is already 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 the function in this test, with an existing email address, it still returns true:

if( is_unique('[email protected]') ) {
    echo "Email is unique";
} else {
    echo "Duplicate email";
}

// Returns true even though [email protected] is in the list

I appreciate anyone's input.

like image 517
Saladon Avatar asked Apr 11 '13 14:04

Saladon


2 Answers

It is fine to use list but you must trim() the item when iterating through the list as they still have the linebreak:

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

Update: As Nick mentioned, the optional flag of FILE_IGNORE_NEW_LINES would dramatically cut down on execution speed and code:

function is_unique($email) {
   $list = file('list.txt',FILE_IGNORE_NEW_LINES);
   return in_array($email,$list) ? false : true;  
}
like image 116
Samuel Cook Avatar answered Sep 28 '22 07:09

Samuel Cook


Either remember to trim your email, or a better solution would be to use FILE_IGNORE_NEW_LINES while you use the file function, which would allow you to use PHP's inbuilt array searching (should be faster). For example:

function is_unique($email) {
   $list = file('list.txt',FILE_IGNORE_NEW_LINES);

   return !in_array($email,$list);
}
like image 27
Nick Avatar answered Sep 28 '22 06:09

Nick