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.

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
Amit Kumar Sharma
  • 262
  • 1
  • 4
  • 12

1 Answers1

19

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!

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
  • Works, except PHP manual says "that array_unique() is not intended to work on multi dimensional arrays". Use with caution. – bbe Feb 07 '17 at 10:18