Looking for duplicate in local text file
php
Solution
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;
}
Problem
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): ``` bob@foo.com sam@bar.com tracy@foobar.com ``` 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('bob@foo.com') ) { echo "Email is unique"; } else { echo "Duplicate email"; } // Returns true even though bob@foo.com is in the list ``` I appreciate anyone's input.