Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_unique for arrays inside array

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"?

like image 580
Ben Avatar asked Mar 06 '11 16:03

Ben


People also ask

How to remove duplicate in array php?

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed. Note: The returned array will keep the first array item's key type.

How to get same value in array in php?

The array_intersect() function compares the values of two (or more) arrays, and returns the matches. This function compares the values of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.

How do I reindex an array?

The re-index of an array can be done by using some inbuilt function together. These functions are: array_combine() Function: The array_combine() function is an inbuilt function in PHP which is used to combine two arrays and create a new array by using one array for keys and another array for values.


2 Answers

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

$arr2 = array_unique($arr, SORT_REGULAR);
like image 134
Tim Cooper Avatar answered Sep 23 '22 18:09

Tim Cooper


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) {
like image 24
mario Avatar answered Sep 20 '22 18:09

mario