Hi everyone, I was just wondering if calling count() on an array actually needs to loop through the array to see how many elements there are, or if the size of the array is stored in the array it's self. I know that the array stores internal pointers to the current element... Is size handled the same way? Is calling count() a free operation?
Thanks !
Ere
Hey,
I can't remember. sizeof() is fast. just:
<?php $arr = array("hello","my","name","is","elfyn"); $arr_count = sizeof($arr); echo "\$arr has $arr_count elements.\n"; ?>
sizeof() is an alias for count(), so if sizeof() is fast, count() is fast. Anyone know for certain how it works though? I'd just like to be sure.
count() works.
It works exactly like elfynmcb says it does. You need to cycle throught the array at all. If you want to use count(), just use the code above, but replace size_of() with count()
I think you guys are missing the point... I know that count() and sizeof() both work... What I'm trying to determine is how they work. If I'm going to create an array by reading in seperate lines from a file, should I keep track of how many lines I've read in for later use, or does the array it's self do that for me and I'm just retrieving that value with count()? The bottom line is whether or not these is any difference (aside for an extra function call on the stack) to using count() as opposed to using the actual size of the array if I know it. I'm trying to be as efficient as possible.
No you dont need to keep track of the size of the array. It will do that for you. Then, when you need to find out how big it is, just use count() or size_of(). That answer your question?
Yep. 🙂