Static code analyzers like (in this specific case) PHPMD bemoan an error in the following piece of PHP code:
foreach ($aSomething as $key => $value) {
... do something with the $key only
}
The error:
Avoid unused local variables such as '$value'.
Now, I am not aware of any way to create a foreach loop with only the keys. What would be the "analyzer safe" solution to phrase these lines?
I am solving this at the moment via a call to array_keys
and then foreach-ing over this one but it feels like overkill. Another solution is always to silence the analyzer for this loop.
What is the "right" way to keep in line with code quality and "understandability" of code requirements?
As I read from some phpmd docs there's a allow-unused-foreach-variables
property for rule UnusedLocalVariable
, read more here:
https://phpmd.org/rules/unusedcode.html
Also, according to github thread here https://github.com/phpmd/phpmd/pull/329, there should be an option to
whitelist variables in the
UnusedLocalVariable
rule
As for using variable like $_
which means "value not needed" or "throw it away", there's another git thread https://github.com/phpmd/phpmd/issues/326, which in the end sends you to previous one with opportunity to "whitelist variables in the UnusedLocalVariable
rule".
So, there're two options - allow unused variables, which I don't think a good idea. Second option is to whitelist variables which will be ignored (the above metioned $_
for example) and use them when you don't need data in these variables.
Although I don't know how to configure phpmd
, I suppose someone will be able to edit my answer with correct configuration for abovesaid options.