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


}

?>
1
  • Open the file for reading. Read the values back into a different array and compare each? Commented Apr 14, 2015 at 19:12

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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 '<script type="text/javascript">alert("Duplicate found. Try again");</script>';?
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);

1 Comment

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 '<script type="text/javascript">alert("Duplicate found. Try again");</script>';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.