Is there a better way than using array-walk in combination with unserialize?

I have two arrays which contain objects. The objects can be same or can be different. I want to merge both arrays and keep only unique objects.

This seems to me like a very long solution for something so trivial. Is there any other way?

class Dummy
{
    private $name;
    public function __construct($theName) {$this->name=$theName;}
}

$arr = array();
$arr[] = new Dummy('Dummy 1');
$arr[] = new Dummy('Dummy 2');
$arr[] = new Dummy('Dummy 3');

$arr2 = array();
$arr2[] = new Dummy('Dummy 1');
$arr2[] = new Dummy('Dummy 2');
$arr2[] = new Dummy('Dummy 3');

function serializeArrayWalk(&$item)
{
    $item = serialize($item);
}

function unSerializeArrayWalk(&$item)
{
    $item = unserialize($item);
}

$finalArr = array_merge($arr, $arr2);
array_walk($finalArr, 'serializeArrayWalk');
$finalArr = array_unique($finalArr);
array_walk($finalArr, 'unSerializeArrayWalk');

var_dump($finalArr);
share|improve this question

feedback

2 Answers

up vote 1 down vote accepted

From here: http://php.net/manual/en/function.array-unique.php#75307

This one would work with objects and arrays also.

<?php
function my_array_unique($array, $keep_key_assoc = false)
{
    $duplicate_keys = array();
    $tmp         = array();       

    foreach ($array as $key=>$val)
    {
        // convert objects to arrays, in_array() does not support objects
        if (is_object($val))
            $val = (array)$val;

        if (!in_array($val, $tmp))
            $tmp[] = $val;
        else
            $duplicate_keys[] = $key;
    }

    foreach ($duplicate_keys as $key)
        unset($array[$key]);

    return $keep_key_assoc ? $array : array_values($array);
}
?>
share|improve this answer
Thank you very much. – Richard Knop Dec 22 '10 at 9:12
@Richard Knop, you are welcome, good luck! – Silver Light Dec 22 '10 at 10:05
feedback

I know there's already an accepted answer, but here's an alternative.

Contrary to the previous answer, it uses in_array() since the nature of comparing objects in PHP 5 allows us to do so. Making use of this object comparison behaviour requires that the array only contain objects, but that appears to be the case here.

$merged = array_merge($arr, $arr2);
$final  = array();

foreach ($merged as $current) {
    if ( ! in_array($current, $final)) {
        $final[] = $current;
    }
}

var_dump($final);
share|improve this answer
Works nice, it might be faster than the other one (dont really know) but i will use yours because i dont have to take make an extra function for it :D – Gigala 2 days ago
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.