1.2.1329. Use List With Foreach

Foreach() structures accepts list() as blind key. If the loop-value is an array with a fixed structure, it is possible to extract the values directly into variables with explicit names.

<?php

// Short way to assign variables
// Works on PHP 7.1, where list() accepts keys.
foreach($names as list('first' => $first, 'last' => $last)) {
    doSomething($first, $last);
}

// Short way to assign variables
// Works on all PHP versions with numerically indexed arrays.
foreach($names as list($first, $last)) {
    doSomething($first, $last);
}

// Long way to assign variables
foreach($names as $name) {
    $first = $name['first'];
    $last = $name['last'];

    doSomething($first, $last);
}

?>

See also list and foreach.

1.2.1329.1. Suggestions

  • Use the list keyword (or the short syntax), and simplify the array calls in the loop.

1.2.1329.2. Specs

Short name

Structures/UseListWithForeach

Rulesets

All, Changed Behavior, Suggestions, Top10

Exakat since

1.0.4

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Features

class

Examples

MediaWiki

Available in

Entreprise Edition, Exakat Cloud