Here is the first draft of an idea that can ultimately work for what you want.
<?php
class DistinctArray implements IteratorAggregate, Countable, ArrayAccess
{
protected $store = array();
public function __construct(array $initialValues)
{
foreach ($initialValues as $key => $value) {
$this[$key] = $value;
}
}
final public function offsetSet( $offset, $value )
{
if (in_array($value, $this->store, true)) {
throw new DomainException('Values must be unique!');
}
if (null === $offset) {
array_push($this->store, $value);
} else {
$this->store[$offset] = $value;
}
}
final public function offsetGet($offset)
{
return $this->store[$offset];
}
final public function offsetExists($offset)
{
return array_key_exists($offset, $this->store);
}
final public function offsetUnset($offset)
{
unset( $this->store[$offset] );
}
final public function count()
{
return count($this->store);
}
final public function getIterator()
{
return new ArrayIterator($this->store);
}
}
$test = new DistinctArray(array(
'test' => 1,
'foo' => 2,
'bar' => 3,
'baz' => '1',
8 => 4,
));
try {
$test[] = 5;
$test[] = 6;
$test['dupe'] = 1;
}
catch (DomainException $e) {
echo "Oops! ", $e->getMessage(), "<hr>";
}
foreach ($test as $value) {
echo $value, '<br>';
}
source
share