Trufa
Trufa

Reputation: 40727

PHP - Why does file_get_contents() behave like this and how a I solve this newline issue?

If I have this code:

$numbers = array_unique(explode(",", file_get_contents('text.txt')));

print_r($numbers);

With this text file:

hello,world,hello

Everything works as expected with the output:

Array ( [0] => hello [1] => world )

I encountered the following problem when changed the text file to this:

hello,
world,
hello

(Just in case, added newlines...)

Now, the output is:

Array ( [0] => hello [1] => world [2] => hello )

I can't fully understand why since ir seems to be exploding correctly but not applying the array_unique(). But that is just my trivial interpretation of the problem, I have no clue as to what is going on here.

I found some other unexpected behavior (unexpected to me at least):

With this text file:

hello,
hello,
hello,
hello,
world,
hello

I had this output:

Array ( [0] => hello [1] => hello [4] => world )

So, the questions:

Thanks in advance!

Upvotes: 0

Views: 726

Answers (3)

Andrew Moore
Andrew Moore

Reputation: 95334

Given the following file:

hello,
world,
hello

PHP sees it as the following string:

hello,\nworld,\nhello

Therefore, when calling explode(',', $fileData), PHP separates the array elements as follows:

[0] hello
[1] \nworld
[2] \nhello

Since all three elements are not unique, array_unique() makes no changes.

Try to trim() all elements before running array_unique() using array_map():

$elements = array_map('trim', $elements);

This will remove all whitespace before and after each element, which will result in the following array:

[0] hello
[1] world
[2] hello

Upvotes: 3

AbiusX
AbiusX

Reputation: 2404

Because first is "Hello" second is "\nWorld" third is "\nHello" and each is unique. var_dump your array to see the difference.

try explode(",\n" ...

Upvotes: 1

Duniyadnd
Duniyadnd

Reputation: 4043

when you explode(",") it's only a comma.

As soon as you created new lines, it adds a \n to it (which is invisible because it does not display a character, but tells the file it's a new line).

You may want to look at file() instead which puts each line into it's own unique array element.

Upvotes: 0

Related Questions