PHP COUNT_RECURSIVE and SplFixedArray

I see some odd behavior with count ($ arr, COUNT_RECURSIVE) when used with SplFixedArray . Take this block of code, for example ...

$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 

A result of 110 would be expected. Is this normal behavior due to the fact that I am inserting SplFixedArray objects?

+4
source share
1 answer

SplFixedArray implements Countable , but Countable does not accept arguments, so you cannot assume it is recursive. The argument is ignored. This can be seen from the signature of the SplFixedArray::count and Countable::count method.

There is a function request for this https://bugs.php.net/bug.php?id=58102


You can attach a SplFixedArray and make it an embedded RecursiveIterator , and then overload the count method to use iterate_count , but then it will always count all the elements, for example. it's always COUNT_RECURSIVE . You can also add a highlighted method.

 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

+6
source

Source: https://habr.com/ru/post/1432512/


All Articles