check for duplicate value in text file/array with php
If there is a file student.txt containing students record as following(first, last name, student ID) like:
John Smith 2320
Mary McHugh 4572
Sara Britny 2322
开发者_运维问答
I wanna check to see if the student ID is unique. if there are duplicated IDs display aan error message with the dupicated ID.
arrayWithId = array
FOR EACH record AS rec IN file
IF arrayWithId NOT CONTAINS rec THEN
ADD rec TO arrayWithId
ELSE
display error
END FOR
# if you get here without any errors displayed there are no duplicates
try this:
$ids = array();
$users = fopen("ciccio.txt", "r"); //open file
while (!feof($users)) {
$line = fgets($users, 4096); //read one line
list ($firstname, $lastname, $id) = explode(" ", $line);
$id = (int)$id;
if (empty($ids)) {
$ids[] = $id;
} else {
if (in_array($id, $ids)) {
echo "Duplicate ID: " . $id . "<br/>";
} else {
$ids[] = $id;
}
}
}
fclose($users); #close file
Just read the file line by line and save all ids. If one id is already saved throw an error.
$line = /* ... */
$data = explode( ", ", $line );
// should contain the id
$id = $data[2];
<?php
$file = "student.txt";
$handle = fopen($file, "r");
$contents = fread($handle, filesize($file));
fclose($handle);
$list = array();
$list = explode("\n",$contents);
$list = array_map("trim", $list);
$current = "foo@bar.com";
echo in_array($current,$list) ? $current.' exists' : $current.' does not exist';
?>
Iterate over the input array, get the ID per item, if the ID is new, store the ID, if not, give error:
$filename = 'students.txt';
$array = file($filename, FILE_IGNORE_NEW_LINES);
$unique = array();
foreach($array as $line => $student)
{
$r = preg_match('/ (\d+)$/', $student, $matches);
if (!$r) continue;
list(,$id) = $matches;
if (isset($unique[$id]))
printf("Duplicate ID found (%d) in '%s' line %d.\n", $id, $student, $line);
else
$unique[$id] = 1;
}
精彩评论