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);
}
?>
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);
}
?>
That's it!
Let me know what you think?
Cover Image credits
Unless it's a very big array, this won't make much difference. Still, I'd use
foreach
instead, because you don't need to keep track of the index then. Better yet, for something like this, I'd usearray_map
.