1.2.1400. Useless Check Before Foreach

There is no need to check the size of an array content before using foreach. Foreach() applies a test on the source, and skips the loop if no element is found.

This rule checks for conditions with sizeof() and count(). Conditions with isset() and empty() are omitted : they also check for the variable existence, and thus, offer extra coverage.

<?php

// Checking for type is good.
if (is_array($array)) {
    foreach($array as $a) {
        doSomething($a);
    }
}

// Foreach on empty arrays doesn't start. Checking is useless
if (!empty($array)) {
    foreach($array as $a) {
        doSomething($a);
    }
}

?>

See also foreach.

1.2.1400.1. Connex PHP features

1.2.1400.1.1. Suggestions

  • Drop the condition and the check

  • Turn the condition into isset(), empty() and is_array()

1.2.1400.1.2. Specs

Short name

Structures/UselessCheck

Rulesets

All, Analyze, CE, CI-checks

Exakat since

0.8.9

PHP Version

All

Severity

Minor

Time To Fix

Instant (5 mins)

Precision

Very high

Examples

Magento, Phinx

Available in

Entreprise Edition, Community Edition, Exakat Cloud