Patrick
Patrick

Reputation: 695

Unused foreach value in static code analyzers

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?

Upvotes: 4

Views: 1406

Answers (2)

Pierre-Olivier Vares
Pierre-Olivier Vares

Reputation: 1769

For those who would have the problem with phpstorm : renaming the variable to $ignored make the analyzer stop complaining.

In fact you can do it in one click with the PHPStorm suggestion : PHPStorm suggestion

Upvotes: 0

u_mulder
u_mulder

Reputation: 54831

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.

Upvotes: 3

Related Questions