0

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
4

2 回答 2

3

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
于 2013-10-06T09:30:00.850 回答
3

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);
于 2013-10-06T09:30:24.680 回答