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
https://forums.phpfreaks.com/topic/235071-finding-dupes-in-array/
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>';

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!

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.