PHP COUNT_RECURSIVE and SplFixedArray
Question
I'm seeing some odd behavior with count( $arr, COUNT_RECURSIVE ) when used with SplFixedArray. Take this block of code, for instance...
$structure = new SplFixedArray( 10 );
for( $r = 0; $r < 10; $r++ )
{
$structure[ $r ] = new SplFixedArray( 10 );
for( $c = 0; $c < 10; $c++ )
{
$structure[ $r ][ $c ] = true;
}
}
echo count( $structure, COUNT_RECURSIVE );
Result...
> 10
You would expect a result of 110. Is this normal behavior due to the fact that I'm nesting SplFixedArray objects?
Solution
SplFixedArray
implements Countable
, but Countable
does not allow for a arguments, hence you cannot count recursive. The argument is ignored. You can see this from the method signature of SplFixedArray::count
and Countable::count
.
There is a Feature Request open for this at https://bugs.php.net/bug.php?id=58102
You can sublass SplFixedArray
and make it implement RecursiveIterator
and then overload the count
method to use iterate_count
but then it will always count all the elements, e.g. it's always COUNT_RECURSIVE
then. Can also add a dedicated method though.
class MySplFixedArray extends SplFixedArray implements RecursiveIterator
{
public function count()
{
return iterator_count(
new RecursiveIteratorIterator(
$this,
RecursiveIteratorIterator::SELF_FIRST
)
);
}
public function getChildren()
{
return $this->current();
}
public function hasChildren()
{
return $this->current() instanceof MySplFixedArray;
}
}