note 110711 added to function.array-unique
| From: | romainbessuges at gmail dot com | Date: | Mon, 26 Nov 2012 20:01:52 +0000 |
| Subject: | note 110711 added to function.array-unique | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-192154@lists.php.net to get a copy of this message | ||
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,
)),
)
?>
----
Server IP: 69.147.83.199
Probable Submitter: 78.192.235.106
----
Manual Page -- http://www.php.net/manual/en/function.array-unique.php
Edit -- https://master.php.net/note/edit/110711
Del: integrated -- https://master.php.net/note/delete/110711/integrated
Del: useless -- https://master.php.net/note/delete/110711/useless
Del: bad code -- https://master.php.net/note/delete/110711/bad+code
Del: spam -- https://master.php.net/note/delete/110711/spam
Del: non-english -- https://master.php.net/note/delete/110711/non-english
Del: in docs -- https://master.php.net/note/delete/110711/in+docs
Del: other reasons-- https://master.php.net/note/delete/110711
Reject -- https://master.php.net/note/reject/110711
Search -- https://master.php.net/manage/user-notes.php