0

I have 2 arrays of data that i want to compare and remove duplicates. I have a MasterArray and a CompareArray. I want to remove all Duplicates in MasterArray. I kind of have this working but its currently case sensitive, which I need to remove. This is where I am struggling.

"Item C" and "e" should not be in the list as it equal if it was not case sensitive.

$MasterArray = array("Item A", "ITEM B", "ITEM C", "d", "E");
$CompareArray = array("Item A", "B", "item c", "d", "e");
$UniqueArray = array_unique( array_merge($MasterArray, $CompareArray) );
$MasterArray = array_diff($UniqueArray, $MasterArray);
print_r($MasterArray); exit;
laurent
  • 88,262
  • 77
  • 290
  • 428
user1315422
  • 45
  • 1
  • 1
  • 6

3 Answers3

0

First convert all the values to lowercase (or uppercase, depending on what you need):

$MasterArray = array_map('strtolower', $MasterArray);
$CompareArray = array_map('strtolower', $CompareArray);

then you can do the comparison:

$UniqueArray = array_unique( array_merge($MasterArray, $CompareArray) );
$MasterArray = array_diff($UniqueArray, $MasterArray);
print_r($MasterArray); 
laurent
  • 88,262
  • 77
  • 290
  • 428
  • I understand i can change the case, but i need to write these back to a database, so i need them in their original case. – user1315422 Sep 30 '16 at 13:50
0

array_udiff + strcasecmp ;)

$MasterArray = array("Item A", "ITEM B", "ITEM C", "d", "E");
$CompareArray = array("Item A", "B", "item c", "d", "e");
print_r( array_udiff($MasterArray, $CompareArray, 'strcasecmp') );
ali_o_kan
  • 452
  • 5
  • 18
0

You can write your own functions where you use a new array $items to store unique values and $dups to store duplicate. Then all you have to do is eliminate $dups from $items and return its values.

For this case, you can use the following function removedups.

function removedups ($MasterArray, $CompareArray) {
    $items = array();
    $dups = array();
    $MasterArray = array_merge($MasterArray, $CompareArray);
    foreach ($MasterArray as $item) {
        $lowercased_item = strtolower($item);
        if (isset($items[$lowercased_item])) {
            unset($items[$lowercased_item]);
            $dups[] = $lowercased_item;
        }
        elseif (!in_array($lowercased_item,$dups)) {
            $items[$lowercased_item] = $item;
        }
    }
    return array_values($items);
}

$MasterArray = array("Item A", "ITEM B", "ITEM C", "d", "E");
$CompareArray = array("Item A", "B", "item c", "d", "e");
$MasterArray = removedups($MasterArray, $CompareArray);
print_r($MasterArray); exit
mano1693
  • 46
  • 2
  • 7