Skip to content

Commit 12c7542

Browse files
committed
Variables set in foreach that's always looped thanks to non-empty arrays cannot be used after the loop
1 parent 88b723f commit 12c7542

File tree

5 files changed

+22
-0
lines changed

5 files changed

+22
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
* `array_keys` (3rd parameter; only if the 2nd parameter `$search_value` is provided)
1616
* `base64_decode` (2nd parameter)
1717
* Variables assigned in `while` loop condition and `for` loop initial assignment cannot be used after the loop.
18+
* Variables set in foreach that's always looped thanks to non-empty arrays cannot be used after the loop.
1819
* Types in `switch` condition and `case` value must match. PHP compares them loosely by default and that can lead to unexpected results.
1920
* Statically declared methods are called statically.
2021
* Disallow `empty()` - it's a very loose comparison (see [manual](https://php.net/empty)), it's recommended to use more strict one.

rules.neon

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
parameters:
22
polluteScopeWithLoopInitialAssignments: false
3+
polluteScopeWithAlwaysIterableForeach: false
34
checkAlwaysTrueCheckTypeFunctionCall: true
45
checkAlwaysTrueInstanceof: true
56
checkAlwaysTrueStrictComparison: true

tests/Levels/LevelsIntegrationTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ public function dataTopics(): array
1313
return [
1414
['arithmeticOperators'],
1515
['onlyBooleans'],
16+
['foreach'],
1617
];
1718
}
1819

tests/Levels/data/foreach-1.json

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
[
2+
{
3+
"message": "Variable $test might not be defined.",
4+
"line": 11,
5+
"ignorable": true
6+
}
7+
]

tests/Levels/data/foreach.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<?php
2+
3+
function () {
4+
foreach ([1, 2, 3] as $val) {
5+
if (rand(0, 1) === 0) {
6+
break;
7+
}
8+
$test = 1;
9+
}
10+
11+
echo $test;
12+
};

0 commit comments

Comments
 (0)