0

I would like to now how to remove duplicates from a multi-dimensional array. I have an array which looks like this:

Array before

Array
(
    [0] => Array
    (
        [0] => 'Hello'
        [1] => 'Test'
    )

    [1] => Array
    (
        [0] => 'Friend'
        [1] => 'Test'
    )

    [2] => Array
    (
        [0] => 'Hello'
        [1] => 'Code'
    )

    [3] => Array
    (
        [0] => 'Hello'
        [1] => 'Test'
    )

    [4] => Array
    (
        [0] => 'hello'
        [1] => 'Test'
    )

    [5] => Array
    (
        [0] => 'Hello'
        [1] => 'Test'
    )
)

And i want it to look like this:

Array after

Array
(
    [0] => Array
    (
        [0] => 'Hello'
        [1] => 'Test'
    )

    [1] => Array
    (
        [0] => 'Friend'
        [1] => 'Test'
    )

    [2] => Array
    (
        [0] => 'Hello'
        [1] => 'Code'
    )

    [3] => Array
    (
        [0] => 'hello'
        [1] => 'Test'
    )
)

As you see, the third and fith element got removed because element zero is identical with them. What is the most efectiv way to solve this? Thank you.

user3877230
  • 439
  • 1
  • 5
  • 18
  • 1
    Duplicate of https://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php – Jon Feb 24 '18 at 09:32
  • Possible duplicate of [How to remove duplicate values from a multi-dimensional array in PHP](https://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php) – Nico Haase Feb 24 '18 at 09:33

3 Answers3

4

You might use array_unique.

Php output demo

$arrays = [
    [
        "Hello",
        "Test"
    ],
    [
        "Friend",
        "Test"
    ],
    [
        "Hello",
        "Test"
    ],
    [
        "hello",
        "Test"
    ]
];

var_dump(array_unique($arrays, SORT_REGULAR));

That would give you:

array(3) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "Hello"
    [1]=>
    string(4) "Test"
  }
  [1]=>
  array(2) {
    [0]=>
    string(6) "Friend"
    [1]=>
    string(4) "Test"
  }
  [3]=>
  array(2) {
    [0]=>
    string(5) "hello"
    [1]=>
    string(4) "Test"
  }
}
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

Another solution could be:

$myArray = array_map("unserialize", array_unique(array_map("serialize", $array)));

You can try it here:

https://repl.it/repls/TrueToughRotation

acontell
  • 6,792
  • 1
  • 19
  • 32
0

Here is another way. No intermediate variables are saved.

We used this to de-duplicate results from a variety of overlapping queries.

$input = array_map("unserialize",array_unique(array_map("serialize", $input)));
Narendra Solanki
  • 1,042
  • 14
  • 20