I have a collection of classes, and I need to filter them whether they're unique in an array.
My approach:
public function unique() {
$uniqueStreams = [];
foreach($this->streams as $stream) {
if(!in_array($stream, $uniqueStreams)) {
$uniqueStreams[] = $stream;
}
}
return new static($uniqueStreams);
}
The problem is, that in_array
only checks for the existance of that classname(at least that's what I've explored), but I need to make sure that they're not identical(it is desired that the instances are from the same class).
As @u_mulder turned out, serializing them and compare the strings is solving the challenge!
public function unique() {
$uniqueStreams = [];
foreach($this->streams as $stream) {
$serialized = serialize($stream);
if(!in_array($serialized, $uniqueStreams)) {
$uniqueStreams[] = $serialized;
}
}
foreach($uniqueStreams as &$uniqueStream) {
$uniqueStream = unserialize($uniqueStream);
}
return new static($uniqueStreams);
}