note 110711 deleted from function.array-unique by googleguy
| From: | googleguy@php.net | Date: | Mon, 26 Nov 2012 22:35:58 +0000 |
| Subject: | note 110711 deleted from function.array-unique by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-192156@lists.php.net to get a copy of this message | ||
Note Submitter: romainbessuges at gmail dot com
----
Just like array_intersect, array_unique computes the string value of each elements. In order to
array_unique an array filled with objects, you have to implement a __toString method :
<?php
class Test {
public $name;
public $id;
public function __toString(){
return $this->name;
}
}
$t1 = new Test();
$t1->id = 1;
$t1->name = "Foo";
$t2 = new Test();
$t2->id = 2;
$t2->name = "Foo";
$t3 = new Test();
$t3->id = 3;
$t3->name = "Bar";
var_dump(array_unique(array($t1, $t2, $t3)));
?>
returns
<?php
array (
0 =>
Test::__set_state(array(
'name' => 'Foo',
'id' => 1,
)),
2 =>
Test::__set_state(array(
'name' => 'Bar',
'id' => 3,
)),
)
?>