php: Optimise forloop with this tip

Chidiebere Chukwudi - Jul 28 '22 - - Dev Community

This is not a long lists of whats and what-not-to-do when using the forloop syntax in php. It's just a tip I got from official php doc. Also this tip is not specific to php

For the following example, take note of the count() method:

Sometimes, It's a common thing to many php developers to iterate through arrays like in the example below.

<?php
$vehicles = array(
    array('name' => 'toyota', 'salt' => 856412),
    array('name' => 'ford', 'salt' => 215863)
);

for($i = 0; $i < count($vehicles); ++$i) {
    $people[$i]['salt'] = mt_rand(000000, 999999);
}
?>
Enter fullscreen mode Exit fullscreen mode

According to official php doc, the above code can be slow because it has to count count($people); the array size for every iteration but most of the time, the size is usually constant hence, you can optimise by using an intermediate variable to hold/store the size instead of repeatedly calling count().. See example below:

<?php
$vehicles = array(
    array('name' => 'toyota', 'salt' => 856412),
    array('name' => 'ford', 'salt' => 215863)
);
$size = count($vehicles);
for($i = 0; $i < $size; ++$i) {
    $people[$i]['salt'] = mt_rand(000000, 999999);
}
?>
Enter fullscreen mode Exit fullscreen mode

That's it!

Let me know what you think?
Cover Image credits

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player