Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Find and display duplicate values across multiple arrays

Tags:

arrays

php

So I am trying to find a way to search through multiple arrays and have it filter out all duplicate entries and have it display what arrays that the duplicate entry was found in.

example:

$array1 = array('domain.com','domain1.com','domain2.com','domain3.com','domain5.com','domaindd5.com');
$array2 = array('domain.com','domain12.com','domain22.com','domain32.com','domain42.com','domain5.com');
$array3 = array('domain.com','domain31.com','domain332.com','domain33.com','domain5.com','domaindd5.com');

then the read out would display something like:

domain.com => array 1, array 2, array 3
domain5.com => array 1, array 3

Thanks in advance for any suggestions

like image 955
Jon Eichler Avatar asked Dec 11 '25 10:12

Jon Eichler


1 Answers

The idea behind this code is simple :) For each entry in all the arrays provided, the The function firstly records the artificial name of the container array in the $raw array, and then removes the entries not having more than one occurrence in that array.

<?php
function duplicates() {
    $raw = array();
    $args = func_get_args();
    $i = 1;
    foreach($args as $arg) {
        if(is_array($arg)) {
            foreach($arg as $value) {
                $raw[$value][] = "array $i";
            }
            $i++;
        }
    }

    $out = array();
    foreach($raw as $key => $value) {
        if(count($value)>1)
            $out[$key] = $value;
    }
    return $out;
}

echo '<pre>';
print_r(
    duplicates(
        array('domain.com','domain1.com','domain2.com','domain3.com','domain5.com','domaindd5.com'),
        array('domain.com','domain12.com','domain22.com','domain32.com','domain42.com','domain5.com'),
        array('domain.com','domain31.com','domain332.com','domain33.com','domain5.com','domaindd5.com')
    )
);
echo '</pre>';
?>

Due to the func_get_args() function, you can provide an arbitrary count of input arrays to the duplicates() function above. Here is an output of the code above:

Array
(
    [domain.com] => Array
        (
            [0] => array 1
            [1] => array 2
            [2] => array 3
        )

    [domain5.com] => Array
        (
            [0] => array 1
            [1] => array 2
            [2] => array 3
        )

    [domaindd5.com] => Array
        (
            [0] => array 1
            [1] => array 3
        )

)
like image 121
someOne Avatar answered Dec 13 '25 01:12

someOne