检查数组中的重复项

时间:2015-04-14 18:04:13

标签: php duplicates

我创建了一个HTML表单,将数据传递给Text文件,文本文件将数据保存在数组中。

在将另一个输入放入数组或文本文件之前,我无法弄清楚如何检查值是否已经存在。

     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);


}

?>

2 个答案:

答案 0 :(得分:0)

为什么不在最后使用该数组之前调用array_unique($myArray);?这将获得数组中的所有唯一值。

在阅读OP评论时编辑:

如果要检查数值是否已存在于数组中:

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

答案 1 :(得分:0)

您可以在完成数组后尝试

$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

相关问题