array_unique在php中没有按预期工作

Yal*_*ber 2 php array-unique

这是一个问题.我正在通过数组中的新行爆炸字符列表.并在其上做独特的数组.但它没有按预期工作.下面是代码:

$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);
Run Code Online (Sandbox Code Playgroud)

结果是

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

oez*_*ezi 7

使用var_dump而不是,print_r你会看到"测试"之间存在差异(看看键盘).

你的代码包含\r\n作为换行符并且你被拆分为\n,所以\r除了最后一个之外,所有的声明仍然存在.

你已经用它array_map来防止这种情况,但在后面的代码中忘了使用retun-value(它不能通过引用工作).将该行更改为:

$list_explode = array_map('trim', $list_explode);
Run Code Online (Sandbox Code Playgroud)

完成此操作后,您将获得所期望的内容(请再次访问键盘).