Does count() really count the all the elements of a PHP array, or is this value cached somewhere and just gets retrieved?
count()
Well, we can look at the source:
/ext/standard/array.c
PHP_FUNCTION(count) calls php_count_recursive(), which in turn calls zend_hash_num_elements() for non-recursive array, which is implemented this way:
PHP_FUNCTION(count)
php_count_recursive()
zend_hash_num_elements()
ZEND_API int zend_hash_num_elements(const HashTable *ht) { IS_CONSISTENT(ht); return ht->nNumOfElements; }
So you can see, it's O(1) for $mode = COUNT_NORMAL.
O(1)
$mode = COUNT_NORMAL
1.4m articles
1.4m replys
5 comments
56.9k users