wael
wael

Reputation: 49

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.

Upvotes: 0

Views: 4965

Answers (5)

JellyBelly
JellyBelly

Reputation: 2431

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

Upvotes: 0

hakre
hakre

Reputation: 197659

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

Upvotes: 0

rahularyansharma
rahularyansharma

Reputation: 10755

<?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 = "[email protected]";

echo in_array($current,$list) ? $current.' exists' : $current.' does not exist';
?>

Upvotes: 0

Marcus
Marcus

Reputation: 12586

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

Upvotes: 1

Tobias
Tobias

Reputation: 9380

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

Upvotes: 0

Related Questions