Hello! There was a sorting task. There are 2 files with a set of lines (approximately 1000), each of which stores a number, for example 345234123 (9 characters - the largest number). It is necessary to compare two arrays and in the second to delete all the lines that are in the first array. How can I do that?

$array1 = file('Yalta.txt'); $array2 = file('Exclude.txt'); $result = array_diff($array1, $array2); foreach ($array1 as $array1) { echo $array1.'<br>'; } print_r($result); 

  • Why is it worth two tags? - Grundy
  • And what have you tried? - Vasily Barbashev
  • @ Vasily Barbashev - he tried to ask a question on ru.stackoverflow.com - Igor
  • php.net/manual/ru/function.array-diff.php help? Only portions are probably desirable to do this - Alexey Shimansky
  • one
    Try to write more detailed questions. To get an answer, explain exactly what you see the problem, how to reproduce it, what you want to get as a result, etc. Give a sample code. - Grundy

2 answers 2

 /** * Работает как file, только обрезает пробельные символы с начала/конца и исключает пустые строки * * @param string $name Имя файла * * @return array Массив НЕ пустых строк, разделённых по переносу */ function getFile($name){ $data = []; array_map(function($str) use (&$data){ $str = trim($str); if(strlen($str) > 0) $data[] = $str; }, file($name)); return $data; } // Читаем через функцию выше, иначе '123' и '123\n' будут разными числами $f = getFile('1.txt'); $s = getFile('2.txt'); // Из второго файла вычитаем первый, тогда второй будет содержать только уникальные строки $data = array_diff($s, $f); $f = fopen('3.txt', 'w'); fwrite($f, implode("\n", $data)); fclose($f); // Пример // 1.txt 123 456 789 // 2.txt 123 000 789 999 // 3.txt 000 999 
  • Thank. I will use - Andrei Sukharev

Alternatively, such an example code:

 $array1 = file('Yalta.txt'); $array2 = file('Exclude.txt'); $filename = "Res.txt"; $result = array_diff($array1, $array2); //$other_mass = serialize($result); $handle = fopen($filename, 'w'); //fwrite($handle, $other_mass); fwrite($handle,implode('',$result)); fclose($handle);