4

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?

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this worked great. That is too bad there is no one function for this. ++ for the great work around!
0

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',
  ),
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.