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

3
  • 3
    $unique = array_unique(explode("\n", file_get_contents('file.txt'))); Commented Nov 14, 2012 at 18:01
  • @nkamm please do not use comments to post solutions. Please delete your above comment. Commented Jan 8, 2018 at 12:40
  • @nkamm One Liner Love it! Commented Dec 17, 2021 at 18:59

4 Answers 4

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));
Sign up to request clarification or add additional context in comments.

4 Comments

that did the trick, but it left a blank line between each one. Is there a way to remove the blank lines?
Oh, sorry. I forgot that file() doesn't remove newline characters. Answer updated. :)
I have a 100MB text file and long rows for which this code is not working. Any alternatives?
@ArushKamboj Maybe checkout stackoverflow.com/questions/4822165/…
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"));

Comments

0

This might work:

$txt = implode('\n',array_unique(explode('\n', $txt)));

3 Comments

Please add some explanation to this code-only answer.
@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.
Try this instead: edit
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 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.