note 96236 deleted from function.count by danbrown

From: Date: Tue, 16 Feb 2010 15:45:14 +0000
Subject: note 96236 deleted from function.count by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-166009@lists.php.net to get a copy of this message
Note Submitter: pinkgothic at gmail dot com ---- yarolan at mail dot ru's observation is, to my relief, no longer true (php 5.3.1, possibly earlier). Using count() in a loop is approximately a linear doubling of cost compared to assigning it before the loop (e.g. 0.2 instead of 0.1). The overhead may at this point simply be from calling a function instead of just reading a variable (evidently by now arrays keep track of the amount of elements they have). This is good news for those of you who do semi-complex array handling in your loops that sometimes changes count() and sometimes doesn't (making keeping-track-of-the-count-in-a-variable-yourself tedious); or those of you who value semantic legibility over performance to a degree. :) Re: ravenswd at gmail dot com legobuff at hotmail dot com's code does not contain an error, because it doesn't set out to retrieve the max' key, just the key of the last element in the array. It does that. :) If you're looking for the max' key, then, indeed, it would have to look something like this: <?php ksort($yourArray); end($yourArray); $index = key($yourArray); ?> But! ravenswd at gmail dot com's solution is quicker. I've not checked, but I imagine the ksort-end-key variant may be somewhat less memory intensive due to lack of another array being created, hence might be useful in a constellation where memory might be more of an issue than CPU. Either way, I figured I'd share.

« previous php.notes (#166009) next »