While extending ArrayIterator, How can i access to current array to modify it? or get some other data from it?
Please consider example below:
class Test extends ArrayIterator {
public function in_array($key) {
return in_array($key, ???);
}
}
Is using $this->getArrayCopy()
instead of ???
ok? Is there any better solution for doing that? What about performance?
And how to change array of class dynamically? for example using array_walk.
Regards,
Notice that the ArrayIterator
class implements ArrayAccess
. To modify the array, simply treat $this as an array:
$this['k'] = 'v';
Unfortunately, functions such as in_array
don't work on array-like objects; you need an actual array. getArrayCopy()
will work, but I would just use (array) $this
.
EDIT: As salathe notes in a comment, getArrayCopy()
is better, because it always gets the internal array, while (array) $this
will behave differently if you use the STD_PROP_LIST
flag.
Performance-wise, making a copy of an array like that does cause a small slowdown. As a benchmark, I tried getArrayCopy()
and (array)
on an ArrayIterator of 1000000 items, and both took about 0.11 seconds on my machine. The in_array
operation itself (on the resulting array), on the other hand, took 0.011 seconds - about a tenth as long.
I also tried this version of the in_array
function:
class Test extends ArrayIterator {
public function in_array($key) {
foreach($this as $v)
if($v == $key)
return true;
return false;
}
}
That function runs in 0.07 seconds on my machine when searching for a value that doesn't exist, which is the worst-case scenario for this algorithm.
The performance problems are too small to matter in most cases. If your situation is extreme enough that 100 nanoseconds or so per array element actually make a difference, then I would suggest putting the values you want to search for in the array keys and using offsetExists()
instead.