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.

2

3 Answers 3

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

Comments

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

Comments

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)));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.