Does count()
really count the all the elements of a PHP array, or is this value cached somewhere and just gets retrieved?
PHP lets you create 2 types of array: Indexed arrays have numeric indices. Typically the indices in an indexed array start from zero, so the first element has an index of 0 , the second has an index of 1 , and so on.
The count() function returns the number of elements in an array.
By default in PHP the array key starts from 0. i.e. 0 => a, 1=> b , I want to reindex the whole array to start from key = 1 i.e 1=> a, 2=> b, .... Is there any reason you can't just use a zero based array? @Jacob, for instance, a for loop that uses % == 0 to define <tr> and <td> tags.
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:
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With