1.2.474. Foreach With list()

Foreach loops have the ability to use list() (or []) as blind variables. This syntax assign directly array elements to various variables.

PHP 5.5 introduced the usage of list in foreach() loops. Until PHP 7.1, it was not possible to use non-numerical arrays as list() wouldn’t support string-indexed arrays. Previously, it was compulsory to extract() the data from the blind array :

<?php
    // PHP 5.5 and later, with numerically-indexed arrays
    foreach($array as list($a, $b)) {
        // do something
    }


    // PHP 7.1 and later, with arrays
    foreach($array as list('col1' => $a, 'col3' => $b)) { // 'col2 is ignored'
        // do something
    }
?>

See also The list function & practical uses of array destructuring in PHP and Array destructuring in PHP.

1.2.474.1. Specs

Short name

Structures/ForeachWithList

Rulesets

All, CompatibilityPHP53, CompatibilityPHP54

Exakat since

0.8.4

PHP Version

With PHP 5.5 and more recent

Severity

Minor

Time To Fix

Slow (1 hour)

Precision

Very high

Features

foreach

Available in

Entreprise Edition, Exakat Cloud