Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - How to test a multidimensional array for duplicate element values in any order

I'm not sure the title really gets across what I'm asking, so here's what I'm trying to do:

I have an array of arrays with four integer elements each, ie.

Array(Array(1,2,3,4), Array(4,2,3,1), Array(18,3,22,9), Array(23, 12, 33, 55))

I basically need to remove one of the two arrays that have the same values in any order, like indices 0 and 1 in the example above.

I can do this pretty easily when there are only two elements to check, using the best answer code in this question.

My multidimensional array can have 1-10 arrays at any given time, so I can't seem to figure out the best way to process a structure like that and remove arrays that have the same numbers in any order.

Thanks so much!

like image 331
Spectre Avatar asked Jul 15 '26 02:07

Spectre


1 Answers

I've been thinking about this, and I think using a well designed closure with array_filter might be the way I'd go about this:

$matches = array();
$array = array_filter($array, function($ar) use (&$matches) {
    sort($ar);
    if(in_array($ar, $matches)) {
        return false;
    }
    $matches[] = $ar;
    return true;
});

See here for an example: http://ideone.com/Zl7tlR

Edit: $array will be your final result, ignore $matches as it's just used during the filter closure.

like image 135
Scopey Avatar answered Jul 17 '26 17:07

Scopey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!