开发者

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 t开发者_如何学Che 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:

  • What is actually going on here?
    • Is it the same issue on both situations?
  • How can I solve this? (without getting rid of the newlines(preferably)).

Thanks in advance!


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


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" ...


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜