note 110076 added to function.count

From: Date: Sun, 16 Sep 2012 22:14:09 +0000
Subject: note 110076 added to function.count
Groups: php.notes 
Request: Send a blank email to php-notes+get-190814@lists.php.net to get a copy of this message
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)); ?> ---- Server IP: 89.31.146.176 Probable Submitter: 88.172.133.112 ---- Manual Page -- http://www.php.net/manual/en/function.count.php Edit -- https://master.php.net/note/edit/110076 Del: integrated -- https://master.php.net/note/delete/110076/integrated Del: useless -- https://master.php.net/note/delete/110076/useless Del: bad code -- https://master.php.net/note/delete/110076/bad+code Del: spam -- https://master.php.net/note/delete/110076/spam Del: non-english -- https://master.php.net/note/delete/110076/non-english Del: in docs -- https://master.php.net/note/delete/110076/in+docs Del: other reasons-- https://master.php.net/note/delete/110076 Reject -- https://master.php.net/note/reject/110076 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#190814) next »