Wednesday, May 20, 2009

Getting Unique Entries From Two Files

Okay, so you have data in one file and then you have updated data in another file. Let's say you have a list of directories that have been searched and they all have a filename, "0.txt". Another file lists all of the directories that have this "0.txt" file but they are actually empty. If you diff the files that will only give you changes being made and won't necessarily give you the entries NOT in the updated file. But, if you get all of the directory entries that are NOT in the new list, then you have a complete list of directories that have a valid file!

*(Well, that was just my example, my real life scenario involved MySQL data.)

Anyhow, with this PHP code you can basically go through both files and utilize in_array to see if certain entries exist in one file or not.

**Note: I wanted to use $argv to handle the arguments, but for some reason file didn't like it. Curious...

$f1 = "/tmp/original.txt";
$f2 = "/tmp/modified.txt";

$a = file($f1);
$b = file($f2);

foreach ($a as $k => $v) {
if (!in_array($v, $b)) {
print "$v";
}
}


Cheers!

No comments: