Remove array duplicates PHP [duplicate]

99封情书 提交于 2019-12-13 05:00:23

问题


How do I remove duplicates from an array?

Let's say that my I have two arrays named $array and $new_array. $array has contents while $new_array is empty, as seen below:

$array = array(5,1,2,1,5,7,10);
$new_array = array();

I want $new_array to store the unique values of $array. It kind of goes like this:

$array = array(5,1,2,1,5,7,10);
$new_array = array(5,1,2,7,10); // removing the 1 and 5 after 2 since those numbers are already a duplicate of the preceding numbers.
echo $new_array; // Output: 512710

回答1:


You can do it through PHP's array_unique function.

This function traverses through your provided array and returns an array with unique values (repeating values will be removed).

Code to return desired string:

$array = array(5,1,2,1,5,7,10);
$new_array = array_unique($array);
echo implode('', $new_array);



回答2:


Use array_unique() and implode():

$array = array(5,1,2,1,5,7,10);
$new_array = array_unique($array);
echo implode('', $new_array);

Output:

512710


来源:https://stackoverflow.com/questions/19207326/remove-array-duplicates-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!