5

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?

1 Answer 1

7

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;
    }
}

demo

1
  • 1
    Exactly what I was looking for. I had checked into that this morning but couldn't find anything. I knew I was overlooking something. Thanks!
    – CVEEP
    Sep 5, 2012 at 15:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.