问题
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