22

I need a function like array_unique for arrays inside array.

The Case - should be equal, but output "not equal":

<?php
$arr=array(array('a',1),array('a',2));
$arr2=array_unique($arr);
if($arr2==$arr){
  echo "equal";
}
else{
  echo "not equal";
}
?>

How should the code be changed to get output "equal"?

3
  • Man, this always comes up. Read the manual, it says "Note that array_unique() is not intended to work on multi dimensional arrays." Commented Mar 6, 2011 at 17:00
  • 5
    I asking for "like" solution, please read my question Commented Mar 6, 2011 at 17:16
  • I don't understand what you mean by "Hi, like array_unique for arrays inside array." Commented Mar 6, 2011 at 17:31

3 Answers 3

54

You should modify your call for array_unique to have it include the SORT_REGULAR flag.

$arr2 = array_unique($arr, SORT_REGULAR);
Sign up to request clarification or add additional context in comments.

Comments

2

If you want to test if the outer array has unique entries, then stringify the inner contents first for a comparison:

$arr1 = array_map("serialize", $arr);
$arr2 = array_unique($arr1);
if ($arr2 == $arr1) {

Comments

-1
function array_unique_when_values_are_serializable($main_array) {
    return array_map('unserialize', array_values(array_unique(array_map('serialize', $main_array))));
}

1 Comment

Please explain your answer. SO exists to teach users, not just answer questions.

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.