Search code examples
phparray-unique

array_unique not working as expected in php


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