7

I am in need to open a text file (file.txt) which contains data in the following format

ai
bt
bt
gh
ai
gh
lo
ki
ki
lo

ultimately I want to remove all the duplicate lines so only one of each data remains. So the result would look like this

ai
bt
gh
lo
ki

any help with this would be awesome

Cesar Bielich
  • 4,754
  • 9
  • 39
  • 81

4 Answers4

26

This should do the trick:

$lines = file('file.txt');
$lines = array_unique($lines);

file() reads the file and puts every line in an array.

array_unique() removes duplicate elements from the array.

Also, to put everything back into the file:

file_put_contents('file.txt', implode($lines));
wassup
  • 2,333
  • 2
  • 21
  • 30
2

Take the php function file() to read the file. You get an array of lines from your file. After that, take array_unique to kick out the duplicates.

In the end, you will have something like

$lines = array_unique(file("your_file.txt"));
David Müller
  • 5,291
  • 2
  • 29
  • 33
0

This might work:

$txt = implode('\n',array_unique(explode('\n', $txt)));
Paul Lo
  • 6,032
  • 6
  • 31
  • 36
taoufiqaitali
  • 460
  • 5
  • 10
  • Please add some explanation to this code-only answer. – mickmackusa Jan 08 '18 at 12:46
  • @mickmackusa: $txt contains the data and `explode()` puts every line in an array (using `\n` delimiter) so we can de-duplicate with `array_unique()`. Everything is then merged back together using `implode()` and the same delimiter. – SuN Dec 02 '19 at 15:37
  • Try this instead: [edit](https://stackoverflow.com/posts/29171605/edit) – mickmackusa Dec 02 '19 at 20:05
0
$lines = file_get_contents('file.txt');
$lines = explode('\n', $lines);
$lines = array_unique($lines);
$lines = implode('\n', $lines);
file_put_contents('file.txt', $lines);
  • 1
    Your answer is in the Review Queue for being low quality and may be deleted. Please add some explanation with your code-only answer so that future readers can fully benefit. Never post code-only answers on SO. – mickmackusa Jan 08 '18 at 12:43