Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: What is the complexity [i.e O(1),O(n)] of the function 'count'? [duplicate]

Tags:

php

What is the Big-O time complexity of the count() function for arrays?

Example

$x = array(1,2,3);
echo count($x); // how many operation does it takes to count the elements 
                // of the array? is it 3, or is it 1
like image 255
Lu4 Avatar asked Dec 30 '10 21:12

Lu4


People also ask

What is the function of count in PHP?

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

How do I count elements in PHP?

How to Count all Elements or Values in an Array in PHP. We can use the PHP count() or sizeof() function to get the particular number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that we can initialize with an empty array.

Which PHP function counts all the values of an array?

The array_count_values() function counts all the values of an array.


1 Answers

$ time php -r '$a=range(1,1000000); $b=0; for($i=0;$i<10;$i++) $b=count($a);'
real    0m0.458s
$ time php -r '$a=range(1,1000000); $a=array(1); $b=0; for($i=0;$i<10;$i++) $b=count($a);'
real    0m0.457s
Seems pretty O(1) to me.

Tested PHP version: PHP 5.3.3-1ubuntu9.1 with Suhosin-Patch (cli) (built: Oct 15 2010 14:00:18)

like image 87
tstenner Avatar answered Oct 13 '22 17:10

tstenner