Jump to content

Finding dupes in array


weep

Recommended Posts

Good day,

 

Is there a simple way to find and list duplicates i an array and insert these to a new one? I have:

 

$array[0] = "asd"

$array[1] = "ter"

$array[2] = "asd"

$array[3] = "asd"

$array[4] = "xfh"

 

From that, I need this:

 

$newarray[0] = "0"

$newarray[1] = "2"

$newarray[2] = "3"

 

I have poked around "array_not_unique" and "in_array" a bit, but can't wrap my head around it enough for it to work... Any and all help are much appreciated. Thanks in advance!

Link to comment
Share on other sites

EDIT: Oh, I could of just used array_diff_key instead :o

 

$array[0] = "asd";
$array[1] = "ter";
$array[2] = "asd";
$array[3] = "asd";
$array[4] = "xfh";

$unique_values = array_unique($array);

$duplicate_values = array_diff_key($array, $unique_values);
echo '<pre>' . print_r($duplicate_values, true) . '</pre>';

 

Original post

I came up with

$array[0] = "asd";
$array[1] = "ter";
$array[2] = "asd";
$array[3] = "asd";
$array[4] = "xfh";

$unique_values = array_unique($array);

$duplicate_values = array();
foreach($array as $key => $value)
{
    if(!array_key_exists($key, $unique_values))
        $duplicate_values[] = $key;
}

echo '<pre>' . print_r($duplicate_values, true) . '</pre>';

Link to comment
Share on other sites

Hi, very sorry for the delay (I'm out on holidays) and thank you for this example! Additional question: Is there a way to limit these to "Where $array is == "something"?

 

Ie:

 

$array[0] = "asd";

$array[1] = "ter";

$array[2] = "asd";

$array[3] = "asd";

$array[4] = "xfh";

$array[5] = "xfh";

 

Your solution would print all dupes, but what if I am interested in only "asd"? How can I extract those, so I get:

 

$newarray[0] = "0"

$newarray[1] = "2"

$newarray[2] = "3"

 

and nothing more. Once again, thanks!

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.