2015-04-14 50 views
0

我已經創建了一個將數據傳遞到文本文件並將文本保存到數組上的數據的HTML表單。檢查數組中的重複

我無法弄清楚如何在數組或文本文件中輸入另一個輸入之前檢查值是否已經存在。

 Name: <input type="text" name="name" /><br /> 
    Email: <input type="text" name="email" /><br /> 
    <input type="submit" name="save" value="Submit" /><br /> 
    <?php 
$myArray = array(); 

if (isset($_POST['save'])) 
{ 
/*The file will be created in the same directory where the PHP code resides 
*a+ to not overwrite text*/ 
$myfile = fopen("DonorList.txt", "a+") or die("Unable to open file!"); 
//get data entered by user from the form 
fwrite($myfile, $_POST['name']); 
fwrite($myfile, " "); 
fwrite($myfile, $_POST['email']); 
fwrite($myfile, "\r\n"); //next line 
fclose($myfile);//close file 

textOutput();//call function 
} 

print_r($myArray); 
//creating function to make code more readable 
function textOutput() 
{ 
    $lines = file('DonorList.txt'); 
    foreach ($lines as $lines_num => $line) 
    { 
     echo "User Input: ".htmlspecialchars($line)."<br />\n"; 
    } 

    $file = fopen("DonorList.txt", "r"); 
    while(!feof($file)) 
    { 
     $myArray[]= fgets($file); 
    } 
    fclose($file); 


} 

?> 
+0

打開文件進行閱讀。將值讀回不同的數組並比較每個值? – jmunsch

回答

0

爲什麼不在最後使用該數組之前調用array_unique($myArray);?這將獲得數組中的所有唯一值。

在閱讀OP評論編輯:

如果你想檢查是否值已經在數組中:

$isInArray = in_array($newValue, $myArray); 
+0

當用戶在HTML表單中輸入值時,如果它與數組中的值匹配,那麼我想要msg發出說重複找到並重試。像這樣:echo''; – user2102787

+0

檢查我的更新,如果你發現它有用。 – taxicala

0

您可以fullfilling陣列

$myArray = array_unique($myArray); 

之後也嘗試您可以在推送之前檢查數值是否已經在陣列中:

while(!feof($file)) 
{ 
    $line = fgets($file); 
    If (!in_array($line, $myArray)) { 
     $myArray[]= $line; 
    } 
} 

這裏有一些關於複雜性的信息:add to array if it isn't there already

+0

獲取未定義的變量:myArray和Warning:in_array()期望參數2爲數組,null爲空。仍然添加到列表中。我該如何告訴用戶請重試echo'';? – user2102787