Last Updated: April 05, 2018
·
2.92K
· donutdan4114

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);

1 Response
Add your response

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 ·