2

Here is a problem. i am exploding a list of character by new line in an array. and doing array unique on it. but it is not working as expected. below is code:

$list = "test
ok
test
test
ok
ok
test";
$list_explode = explode("\n", $list); //exploding the characters of the list from the input
//displaying unique 

array_map('trim', $list_explode);
$result = array_unique($list_explode);
print_r($result);

The result is

Array ( [0] => test [1] => ok [6] => test )

skaffman
  • 398,947
  • 96
  • 818
  • 769
Yalamber
  • 7,360
  • 15
  • 63
  • 89

3 Answers3

7

use var_dump instead of print_r and you'll see there difference between the "test"s (take a look at codepad).

your code contains \r\n as linebreaks and you're splittoing at \n, so \r is still there at all entrys except the last one.

you're already using array_map to prevent this but forgot to use the retun-value (it doesn't work by reference) in the latter code. change that line to:

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

after doing this, you'll get what you expect (see at codepad again).

oezi
  • 51,017
  • 10
  • 98
  • 115
2

You've failed to take into account that your string has a sequence of \r\n for the line break. In exploding you've only removed the \n portion so what your result actually looks like is:

Array ( [0] => test\r [1] => ok [6] => test )

However, the \r does not print as a visible character (even though the code sees it).

Joel Etherton
  • 37,325
  • 10
  • 89
  • 104
1

You can split multiple lines of text in two main ways:

  1. Use $list_explode = array_map('rtrim', explode("\n", $list));

  2. Use $list_explode = preg_split("/\r?\n/", $list);

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309