1.2.1247. Unconditional Break In Loop

An unconditional break in a loop creates dead code. Since the break is directly in the body of the loop, it is always executed, creating a strange loop that can only run once.

Here, break may also be a return, a goto or a continue. They all branch out of the loop. Such statement are valid, but should be moderated with a condition.

<?php

// return in loop should be in
function summAll($array) {
    $sum = 0;

    foreach($array as $a) {
        // Stop at the first error
        if (is_string($a)) {
            return $sum;
        }
        $sum += $a;
    }

    return $sum;
}

// foreach loop used to collect first element in array
function getFirst($array) {
    foreach($array as $a) {
        return $a;
    }
}

?>

1.2.1247.1. Connex PHP features

1.2.1247.1.1. Suggestions

  • Remove the loop and call the content of the loop once.

1.2.1247.1.2. Specs

Short name

Structures/UnconditionLoopBreak

Rulesets

All, Analyze, CE, CI-checks

Exakat since

0.12.16

PHP Version

All

Severity

Major

Time To Fix

Quick (30 mins)

Precision

Very high

Examples

LiveZilla, MediaWiki

Available in

Entreprise Edition, Community Edition, Exakat Cloud