- rand: documentation ( source)
<?php
class A
{
public $val;
public function __construct($val) { $this->val = $val; }
}
$storage = new SplObjectStorage;
$storage->attach(new A(1));
$storage->attach(new A(2));
$storage->attach(new A(3));
$storage->attach(new A(4));
$storage->attach(new A(5));
$storage->attach(new A(6));
$storage->attach(new A(7));
$storage->attach(new A(8));
$storage->attach(new A(9));
$storage->attach(new A(10));
$storage->rewind();
$iterated = 0;
$expected = count($storage);
while ($storage->valid()) {
$iterated++;
$object = $storage->current();
//echo $iterated . '(' . $object->val . ') - ';
$storage->next();
if(rand(0,1) === 1) {
// echo ' ' . $object->val . ' ';
$storage->detach($object);
continue;
}
// echo PHP_EOL;
}
if(count($storage) != $expected) {
echo 'Error!' . PHP_EOL;
}
exit;