4

What would be the most efficient way of either removing dups or creating new array with no dups? Are there any built in PHP functions that save this manual removal?

[2013-05-27 22:35:55]: Array
(
    [0] => stdClass Object
        (
            [type] => 1
            [val] => 1111
        )

    [1] => stdClass Object
        (
            [type] => 1
            [val] => 2222
        )

    [2] => stdClass Object
        (
            [type] => 1
            [val] => 1111
        )

    [3] => stdClass Object
        (
            [type] => 1
            [val] => 2222
        )
)

Many thanks, Luke

Luke G
  • 1,741
  • 6
  • 23
  • 34
  • 1
    look here http://stackoverflow.com/questions/4507518/will-array-unique-work-also-with-array-of-objects – user4035 May 27 '13 at 22:05
  • $final = array(); foreach ($merged as $current) { if ( ! in_array($current, $final)) { $final[] = $current; } } var_dump($final); – Luke G May 28 '13 at 07:00
  • 4
    [**`array_unique`**](http://php.net/manual/en/function.array-unique.php) works with an array of objects using **`SORT_REGULAR`**. See my answer: http://stackoverflow.com/questions/4507518/will-array-unique-work-also-with-array-of-objects/18203564#18203564 – Matthieu Napoli Aug 13 '13 at 07:54

3 Answers3

3

I doubt that there is anything faster than a foreach() loop in this case.

SteAp
  • 11,853
  • 10
  • 53
  • 88
2

Well first of all, you have to decide on what you mean with duplicates, for example in the array above, the items in 0 and 2 could refer to the same instance, or it could be two completely different instances.

Take a look here to see more about comparing objects in PHP.

In short, if by duplicate you mean a reference to the same object, then you're in luck because that's really easy using array_unique:

array_unique($array);

Will do the job.

On the other hand if you want to remove objects that have the same values, which I'm guessing is less likely, then you can go with array_filter which takes a callback function for you to remove the items in the array. I leave the programming of the callback to you. ;)

Daniel Figueroa
  • 10,348
  • 5
  • 44
  • 66
0

array_unique should be able to help you. array_unique

See this codepad here

Ian Brindley
  • 2,197
  • 1
  • 19
  • 28