Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is PHP's count() function O(1) or O(n) for arrays?

Does count() really count the all the elements of a PHP array, or is this value cached somewhere and just gets retrieved?

like image 925
Dexter Avatar asked Apr 29 '11 17:04

Dexter


People also ask

Does PHP array start at 0 or 1?

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.

What does count () function do in PHP?

The count() function returns the number of elements in an array.

Does PHP array start at 1?

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.


1 Answers

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.

like image 146
Vladislav Rastrusny Avatar answered Sep 19 '22 19:09

Vladislav Rastrusny