1.2.472. For Using Functioncall¶
It is recommended to avoid functioncall in the for() statement.
This is true with any kind of functioncall that returns the same value throughout the loop.
Make sure that the functioncall doesn’t change with the loop.
<?php
// Fastest way
$nb = count($array);
for($i = 0; $i < $nb; ++$i) {
doSomething($i);
}
// Same as above, but slow
for($i = 0; $i < count($array); ++$i) {
doSomething($i);
}
// Same as above, but slow
foreach($portions as &$portion) {
// here, array_sum() doesn't depends on the $grade. It should be out of the loop
$portion = $portion / array_sum($portions);
}
$total = array_sum($portion);
foreach($portion as &$portion) {
$portion = $portion / $total;
}
?>
See also PHP for loops and counting arrays.
1.2.472.1. Connex PHP features¶
1.2.472.1.1. Suggestions¶
Call the function once, before the loop
Replace by a foreach structure
1.2.472.1.2. Specs¶
Short name |
Structures/ForWithFunctioncall |
Rulesets |
|
Exakat since |
0.8.4 |
PHP Version |
All |
Severity |
Minor |
Time To Fix |
Slow (1 hour) |
Precision |
High |
ClearPHP |
|
Available in |