Last Updated: April 05, 2018
· donutdan4114
Drupal logo 1

PHP count() is very slow.

Don't be stuck making this mistake, which I've seen many times:

for($i = 0; $i < count($my_array); $i++){ ... }

For the uninitiated, the $i < count($my_array) and $i++ are run every time the loop cycles. To alleviate this computationally intensive operation, simply set a variable:

$count = count($my_array);
for($i = 0; $i < $count; $i++){ ... }

*hint: the same idea applies to a while and do loop.

while($i < $count){ $i++; }

do{ $i++; }while($i < $count);
Say Thanks

1 Response
Add your response

Drupal logo 1

This site http://m.metamorphosite.com/php-benchmarks-loops-arrays would suggest that foreach loops are actually very fast most of the time. However, I think they naturally take up more memory when you're using them. But using references can fix that:

foreach($myarray as &$ref){ ... }
over 1 year ago ·