1.2.1338. 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);
}
?>
1.2.1338.1. Connex PHP features¶
1.2.1338.1.1. Suggestions¶
Use the list keyword (or the short syntax), and simplify the array calls in the loop.
1.2.1338.1.2. Specs¶
Short name |
Structures/UseListWithForeach |
Rulesets |
|
Exakat since |
1.0.4 |
PHP Version |
All |
Severity |
Minor |
Time To Fix |
Quick (30 mins) |
Precision |
Very high |
Examples |
|
Available in |