1.2.1107. Should Use Foreach

Use the foreach loop instead of for when traversing an array.

Foreach() is the modern loop : it maps automatically every element of the array to a blind variable, and iterate. This is faster and safer.

<?php

// Foreach version
foreach($array as $element) {
    doSomething($element);
}

// The above case may even be upgraded with array_map and a callback,
// for the simplest one of them
$array = array_map('doSomething', $array);

// For version (one of various alternatives)
for($i = 0; $i < count($array); $i++) {
    $element = $array[$i];
    doSomething($element);
}

// Based on array_pop or array_shift()
while($value = array_pop($array)) {
    doSomething($array);
}

?>

See also foreach and 5 Ways To Loop Through An Array In PHP.

1.2.1107.1. Suggestions

  • Move for() loops to foreach(), whenever they apply to a finite list of elements

1.2.1107.2. Specs

Short name

Structures/ShouldUseForeach

Rulesets

All, Suggestions

Exakat since

0.12.7

PHP Version

All

Severity

Minor

Time To Fix

Instant (5 mins)

Precision

Very high

Features

foreach, for

Examples

ExpressionEngine, Woocommerce

Available in

Entreprise Edition, Exakat Cloud