PHP

PHP

Made by DeepSource

Use of compute intensive function in loop condition PHP-P1000

Performance
Critical

One or more compute intensive functions like count, database calls(mysqli_query, mysqli_fetch_assoc, etc.) is being used in the loop condition. Though using these functions is a cheap operation; however, there's still the function call overhead when calling it on each iteration.

It is recommended to copy the result of the function into an variable outside the loop condition.

Bad practice

// `count()` function is called each time the loop iterates
for ($i = 0; $i < count($array); $i++) {
    echo $array[$i], PHP_EOL;
}

Recommended

// `count()` function is called only once
$arrayCount = count($array);
for ($i = 0; $i < $arrayCount; $i++) {
    echo $array[$i], PHP_EOL;
}