1.2.1126. Simplify Foreach

Remove all unused keys or values from a foreach() call. This prevents PHP from assigning them for nothing, and save some processing time.

This is a micro-optimisation.

<?php

// No key usage
foreach($array as $key => $value) {
    echo $value;
}

// No value usage
foreach($array as $key => $value) {
    echo $key;
}

?>

1.2.1126.1. Suggestions

  • Use array_keys() or array_values() to simplify the source array

  • Remove the call to $key => when the key is not used in the loop

1.2.1126.2. Specs

Short name

Performances/SimplifyForeach

Rulesets

All, Performances

Exakat since

2.3.7

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

High

Features

foreach

Available in

Entreprise Edition, Exakat Cloud