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
1
  • 1
    This question appears to be off-topic because a cursory Google search would give you the answer a thousand-fold. Commented Oct 6, 2013 at 9:34

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

OMG thanks! So does that mean that $new_array now stores the unique values of $array?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.