Jump to content

arrays: if duplicate, remove value


levivel

Recommended Posts

Hello,

I would like to ask for your kind assistance in this difficulty:
I merged two arrays in one. In this merged array, there will be duplicate values. I would like to take those duplicate values and remove them - both, not only the duplicate value, but the original too. At the end, I would like to end up with an array with only values that did not have a duplicate after the merge.

I've been searching for a solution, but this issue seems very similar to removing only the duplicate value and all my results seem to point me to the array_unique function, which does not do what I would like to.

I appreciate any suggestions.
Thanks,
L
Link to comment
https://forums.phpfreaks.com/topic/19551-arrays-if-duplicate-remove-value/
Share on other sites

or you could use the [url=http://us2.php.net/array_unique]array_unique()[/url] function

[code]<?php

$data1 = array(1,2,3,4,5,6);
$data2 = array(2,4,6,8);
$data = array_merge($data1, $data2);

$uniquedata = array_unique($data);

echo '<pre>', print_r($uniquedata, true), '</pre>';
?>[/code]
Got it, I've read the question more closely now instead of leaping in on reading the title. Still on my my first coffee of the morning.

Faster method

[code]foreach ($data2 as $val) {
    if ($k = array_search($val,$data1)) {
        unset ($data1[$k]);
    }
    else $data1[] = $val;
}

echo '<pre>', print_r($data1, true), '</pre>';[/code]

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.