Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 检查数组中是否存在重复项_Php_Duplicates - Fatal编程技术网

Php 检查数组中是否存在重复项

Php 检查数组中是否存在重复项,php,duplicates,Php,Duplicates,我创建了一个HTML表单,将数据传递到文本文件,文本文件将数据保存在数组中 在将另一个输入放入数组或文本文件之前,我不知道如何检查值是否已经存在 Name: <input type="text" name="name" /><br /> Email: <input type="text" name="email" /><br /> <input type="submit" name="save" value="Sub

我创建了一个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);


}

?>
名称:
电子邮件:


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

阅读评论后编辑:

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

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

您可以在填充完数组后重试

$myArray = array_unique($myArray);
您还可以在推送该值之前检查该值是否已在数组中:

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

这里有一些关于复杂性的信息:

获取未定义的变量:myArray和警告:in_array()希望参数2是数组,在中给出null。仍在添加到列表中。我如何告诉用户请重试回显“警报”(“发现重复。重试”);?当用户在HTML表单中输入值,并且如果它与数组中的值匹配,那么我希望msg输出,并说找到了重复项,然后重试。类似这样的内容:echo'alert(“找到重复项。重试”);打开文件进行读取。将这些值读回不同的数组,并进行比较?