note 110076 deleted from function.count by googleguy

From: Date: Mon, 17 Sep 2012 00:07:02 +0000
Subject: note 110076 deleted from function.count by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-190820@lists.php.net to get a copy of this message
Note Submitter: F. G. ---- The internal structure of a PHP array contains is size, so count() runs in constant time (it does not iterate among the values). So in the 2 following loops, the second one does not optimize anything: <?php for ($i=0; $i<count($a); $i++) { ; } $count = count($a); for ($i=0; $i<$count; $i++) { ; } // this is NOT faster ?> Also note that "foreach" should generally be used instead of "for" in such loops over an array. Another common misconception: if $o is an object, count($o) won't always equal 1. If the class of $o implements the SQL interface Countable, then count() will call a method of $o to get this value. Two examples of count() that fix common misuses: * To count the non-empty values of $a: <?php echo count(array_filter($a)); ?> * To get a random element of a numeric array: <?php echo $a[rand(0, count($a)); ?>

« previous php.notes (#190820) next »