0

I have created a HTML form that passes data to Text file and text file saves data on the array.

I cannot figure out how to go about checking to see if value already exists before putting another input in the Array or text file.

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


}

?>
HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47

2 Answers2

0

Why not call array_unique($myArray); before you use that array at the end? This will get all unique values in the array.

EDIT upon reading OP comment:

If you want to check if the value is already in the array:

$isInArray = in_array($newValue, $myArray);
taxicala
  • 21,408
  • 7
  • 37
  • 66
  • when user enters the Value in HTML form and if it matches the value in array, then i want msg out saying duplicate found and to retry. something like this : echo ''; – user2102787 Apr 14 '15 at 18:25
0

You may try after fullfilling the array

$myArray = array_unique($myArray);

Also you can check if the value is already in the array before pushing it:

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

Here you have some info about complexity: add to array if it isn't there already

Community
  • 1
  • 1
Kevin
  • 149
  • 10
  • getting Undefined variable: myArray and Warning: in_array() expects parameter 2 to be array, null given in . Still adding to the list. How can i tell user to please retry echo '';? – user2102787 Apr 14 '15 at 18:22