Finding Difference Between Two Files with PHP

By | May 12, 2008

Today I will show you a short and effective solution to “minus” one file from another. The first solution uses PHP’s array_diff function and is useful when your files are not too big as this method consumes server RAM if you create big arrays. Here is the code:

<?
$file1=file(“plus.txt”);
$file2=file(“minus.txt”);

$hopa=array_diff($file1, $file2);
?>

$hopa is the array that contains all elements of the first file that are not found in the second one.

The second solution is similar to this but uses another algorithm and is more suitable for big files.

<?
$gd=array(“1”, “2”, “3”, “4”, “5”, “6”, “7”);
$acc=fopen(“file.txt”, “r”);

while (!feof($acc))
{
$aa=fgets($acc);
// Choose the solution you like – uncomment one of the strings below
// The first way to do this is to compare length before and after replace
//if (strlen(str_replace($gd, “”, $aa))!=strlen($aa)) echo $aa.”rn”;
// if you like, you can check if the value exists in array
// if (in_array($aa, $gd)) echo $aa.”rn”;
}
fclose($acc);
?>

This code is suitable when the second file or array that contains “bad” elements is relatively small as it is loaded into memory. If you have the possibility to increase limits you should do it before working with big files.