Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I need to check the 2D array($arr) for any duplicates(order does not matter) and put them into a clean array.

For example:

$arr = array ( 
    array (-9,1,8 ), 
    array (-9,2,7 ),
    array (-9,3,6 ),
    array (-9,4,5 ),
    array (-9,5,4 ),
    array (-9,6,3 ),
    array (-9,7,2 ),
    array (-9,8,1 )
)

needs to be end up being:

$cleanArr = array ( 
    array (-9,1,8 ), 
    array (-9,2,7 ),
    array (-9,3,6 ),
    array (-9,4,5 )
)

or

$cleanArr =  array(     
    array (-9,5,4 ),
    array (-9,6,3 ),
    array (-9,7,2 ),
    array (-9,8,1 )
)

Is there a PHP function for this or do I need to do some sort of loop to clean out the duplicates?

share|improve this question

2 Answers 2

up vote 5 down vote accepted

No function does this outright, you could use a combination of functions though. You could first sort all of sub batches of array first into ascending order first, then serialize each on them, utilize array_unique, then unserialize again to have that multi dimensional again:

foreach($arr as &$a){ sort($a); }
$arr = array_map('unserialize', array_unique(array_map('serialize', $arr)));
print_r($arr);
share|improve this answer
    
Yes, this worked great. That is too bad there is no one function for this. ++ for the great work around! –  Icewine 6 hours ago
    
@Icewine sure im glad this helped –  Ghost 5 hours ago

Try this:

    <?php

    $arr = array ( 
    array (-9,1,8 ), 
    array (-9,2,7 ),
    array (-9,3,6 ),
    array (-9,4,5 ),
    array (-9,5,4 ),
    array (-9,6,3 ),
    array (-9,7,2 ),
    array (-9,8,1 )
    );

    $arr = array_map(function($n) {return explode(',', $n);}, (array_unique(array_map(function($n) {sort($n); return implode(',', $n);}, $arr))));

echo var_export($arr, true);

?>

Output:

array (
  0 => 
  array (
    0 => '-9',
    1 => '1',
    2 => '8',
  ),
  1 => 
  array (
    0 => '-9',
    1 => '2',
    2 => '7',
  ),
  2 => 
  array (
    0 => '-9',
    1 => '3',
    2 => '6',
  ),
  3 => 
  array (
    0 => '-9',
    1 => '4',
    2 => '5',
  ),
)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.