dbso
dbso

Reputation: 696

PHP read from file into array and remove duplicates (loop)

I've googled a bit now, but can't find anything that works for me.

I have a textfile containing: username;firstname;lastname;classcode\n

I use this while-loop to get content out:

$handle = fopen("studen.txt", "r");

while(!feof($handle)) {

$linje = fgets($handle);

$larray = explode(";",$linje);

$klassekode = trim($larray[3]);

}

$larray[3] is the only thing I'm interested in here. I want to make a html-list out of this, so I used:

echo "<option value=\"$klassekode\">$klassekode</option>";

My problem now is that I can't seem to find a way to remove the duplicate entries. There are now 3 "IS1", 4 "IS3" and so on. I suspect there's a easy solution for this that I simply can't figure out :-|

Thanks in advance!

Upvotes: 2

Views: 926

Answers (3)

newfurniturey
newfurniturey

Reputation: 38416

A quick way, without much code modification, would be to keep a second array of every value you've already seen and if the current value exists in it, skip it:

$seenValues = array();

$handle = fopen("studen.txt", "r");
while(!feof($handle)) {
    $linje = fgets($handle);
    $larray = explode(";",$linje);
    $klassekode = trim($larray[3]);

    if (in_array($klassekode, $seenValues)) continue; // skip it
    $seenValues[] = $klassekode;
    // do your other stuff
}

Using the same method as above, but more efficient, would be to use the $klassekode value as the index in the $seenValues array and use PHP's isset() instead. It's way faster than using the in_array() method, so if there are a lot of these entries and speed is important, try this instead:

...
if (isset($seenValues[$klassekode])) continue; // skip it
$seenValues[$klassekode] = true;
...

Upvotes: 1

codaddict
codaddict

Reputation: 454970

Since classcode is the 3rd field in the line it is available in $larray[2] and not in $larray[3].

Next to de-duplicate you can make use of another array. Arrays in PHP can act like hashes or sets. Every time you explode and get a new class code you put it in an array and at the end you just use the elements from this array as your classcodes.

Upvotes: 0

Baba
Baba

Reputation: 95101

You can use array_unique to remove duplicate and file to read the file in to an array

$content = array_unique(file("studen.txt"));
foreach ( $content as $var ) {
    list($userame, $klassekode, $klassekode) = explode(";", $var);
    printf("<option value=\"%s\">%s</option>", $klassekode, $klassekode);
}

Upvotes: 0

Related Questions