G
G
germn2012-03-20 10:36:17
PHP
germn, 2012-03-20 10:36:17

How to uniqueize an array of object references by the references themselves, and not by the value of the objects?

$a = 1;
        $b = 2;

        $array[] = &$a; // Два элемента - ссылка на $a
        $array[] = &$a;

        $array[] = &$b; // Один элемент - ссылка на $b
        
        $array[0]++;
        // Естественно изменилось и значение $array[1]:
        print_r($array);
        // Array ( [0] => 2 [1] => 2 [2] => 2 )
        
        print_r(array_unique($array));
        // Array ( [0] => 2 ) 
        // Из трех ссылок, две из которых уникальны, осталась только одна

I want the output of the uniqueization operation to be an array containing one reference to $a and one to $b.
How to implement?
Thank you!
Upd:
How do you even compare two references for equivalence?
For the code above:
$array[0] === $array[1] // true
$array[0] === $array[2] // true :(

The answer to this question was suggested in the comments:
function is_ref_to(&$a, &$b)
{
    $t = $a;
    if($r=($b===($a=1))){ $r = ($b===($a=0)); }
    $a = $t;
    return $r;
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
mark_ablov, 2012-03-20
@germn

Write your own version of array_unique, because the comparison inside the library is based on string values ​​- (string)s1 == (string)s2.

B
BoShurik, 2012-03-20
@BoShurik

spl_object_hash won't work?
There will be something like:
$id = spl_object_hash($a);
$array[$id] = $a;

S
Stdit, 2012-03-20
@Stdit

$s = new SplObjectStorage();
$o1 = new StdClass;
$o1->a = 1;
$o2 = new StdClass;
$o2->a = 1;
$o3 = new StdClass;
$o3->b = 3;
$s->attach($o1);
$s->attach($o2);
$s->attach($o1);
$s->attach($o3);
var_dump(iterator_to_array($s));
array(3) {
  [0]=>
  object(stdClass)#2 (1) {
    ["a"]=>
    int(1)
  }
  [1]=>
  object(stdClass)#3 (1) {
    ["a"]=>
    int(1)
  }
  [2]=>
  object(stdClass)#4 (1) {
    ["b"]=>
    int(3)
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question