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.
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;  
}
                        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);
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With