6

I want to get a solution in PHP to get unique array based on sub array bases. Like this

Array
(
[0] => Array
    (
        [0] => 1227
        [1] => 146
        [2] => 1
        [3] => 39
    )

[1] => Array
    (
        [0] => 1227
        [1] => 146
        [2] => 1
        [3] => 39
    )

[2] => Array
    (
        [0] => 1228
        [1] => 146
        [2] => 1
        [3] => 39
    )
)

to

Array
(
[0] => Array
    (
        [0] => 1227
        [1] => 146
        [2] => 1
        [3] => 39
    )

[1] => Array
    (
        [0] => 1228
        [1] => 146
        [2] => 1
        [3] => 39
    )

)

I mean to say array[1] should be removed as array[0] and array[1] are the same. I tried to use array_unique but it didn't work for me.

5
  • I think this does exactly what you want: stackoverflow.com/questions/307674/… Commented Sep 28, 2013 at 16:13
  • You both did not really read the OPs question, I'd say... Commented Sep 28, 2013 at 16:14
  • I believe he wants to remove duplicate sub-arrays from his array. The question i linked solved that, I believe Commented Sep 28, 2013 at 16:15
  • I search goold and stackoverflow but could found that solution... might be not using correct keywords. Commented Sep 28, 2013 at 16:16
  • How can I link this quesiton to Hless's answers Commented Sep 28, 2013 at 16:17

1 Answer 1

20

This can be done with array_unique but you'll also need to use the SORT_REGULAR (PHP 5.2.9+) flag:

$array = array(
    array(1227, 146, 1, 39),
    array(1227, 146, 1, 39),
    array(1228, 146, 1, 39),
);
$array = array_unique($array, SORT_REGULAR);

Output:

Array
(
    [0] => Array
        (
            [0] => 1227
            [1] => 146
            [2] => 1
            [3] => 39
        )

    [2] => Array
        (
            [0] => 1228
            [1] => 146
            [2] => 1
            [3] => 39
        )

)

Demo!

For older versions of PHP, you could use the solution I linked to in the question's comments:

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

Hope this helps!

Sign up to request clarification or add additional context in comments.

1 Comment

Works, except PHP manual says "that array_unique() is not intended to work on multi dimensional arrays". Use with caution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.