array_unique not working as expected in php
-
07-06-2021 - |
Question
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 )
Solution
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).
OTHER TIPS
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).
You can split multiple lines of text in two main ways:
Use
$list_explode = array_map('rtrim', explode("\n", $list));
Use
$list_explode = preg_split("/\r?\n/", $list);