Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Check for duplicate values in a multidimensional array

I have this issue with multidimensional arrays.

Given the following multidimensional array:

Array(
[0] => Array("a", "b", "c")
[1] => Array("x", "y", "z")
[2] => Array("a", "b", "c")
[3] => Array("a", "b", "c")
[4] => Array("a", "x", "z")
)

I want to check its values and find duplicates (i.e. keys 0, 2 and 3) leaving just one key - value pair deleting the others, resulting in somthing like this:

Array(
    [0] => Array("a", "b", "c")
    [1] => Array("x", "y", "z")
    [2] => Array("a", "x", "z")
    )

How can I do that??

like image 586
Maldoror Avatar asked Feb 09 '11 18:02

Maldoror


People also ask

How can we get duplicate values in multidimensional array in PHP?

To merge the duplicate value in a multidimensional array in PHP, first, create an empty array that will contain the final result. Then we iterate through each element in the array and check for its duplicity by comparing it with other elements.

How do you find duplicates in a 2d array?

Here's a brute-force straight forward way of counting duplicates. Turn the 2d array into a 1d array ( List<Integer> ), then loop through the 1d array counting the duplicates as you find them and removing them so you don't count them more than once.

How do you check if there are duplicate elements in an array?

function checkIfArrayIsUnique(myArray) { for (var i = 0; i < myArray. length; i++) { for (var j = i+1; j < myArray. length; j++) { if (myArray[i] == myArray[j]) { return true; // means there are duplicate values } } } return false; // means there are no duplicate values. }

How do you find duplicates in a matrix?

Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.


2 Answers

This will remove duplicate items from your array using array_unique():

$new_arr = array_unique($arr, SORT_REGULAR);
like image 178
Tim Cooper Avatar answered Nov 03 '22 04:11

Tim Cooper


You can simply do it using in_array()

$data = Array(
    0 => Array("a", "b", "c"),
    1 => Array("x", "y", "z"),
    2 => Array("a", "b", "c"),
    3 => Array("a", "b", "c"),
    4 => Array("a", "x", "z"),
);

$final = array();
foreach ($data as $array) {
    if(!in_array($array, $final)){
        $final[] = $array;
    }
}

which will get you something like

array(3) {
  [0] => array(3) {
    [0] => string(1) "a"
    [1] => string(1) "b"
    [2] => string(1) "c"
  }
  [1] => array(3) {
    [0] => string(1) "x"
    [1] => string(1) "y"
    [2] => string(1) "z"
  }
  [2] => array(3) {
    [0] => string(1) "a"
    [1] => string(1) "x"
    [2] => string(1) "z"
  }
}
like image 30
JF Dion Avatar answered Nov 03 '22 02:11

JF Dion