Remove this unused "$var" local variable

  • ALM used: GitHub
  • CI system used (not sure)
  • Languages of the repository: PHP
  • Error observed: Remove this unused "$key" local variable
  • Steps to reproduce

Create a foreach in PHP that loops over an associative array with these properties:

$array = array(
    'key_one' => 'value_one_which_might_be_an_object_or_array',
    'key_two' => 'value_two_which_might_be_an_object_or_array',

Then, in your foreach you will want only to use the values.
Thus, you separate key and value:

foreach( $array as $key => $value ) {

You never use the key, because it is needless in this operation. You are only interested in the values.

I see nothing wrong with this approach but SonarCloud says I have to remove the never-used $key

  • Potential workaround

None, other than breaking my code or using the $key for some needless operation?

What do I miss?


Are you using SonarCloud or SonarQube? And if the latter, which version?



I had posted this initially in that “help” forum but it was moved, sorry.


Thanks. This is flagged for more expert attention. Hopefully, they’ll be along soon.


1 Like


If you only care about the values contained in the array, why don’t you write your loop in the following way?

foreach( $array as $value ) {

Well, what can I say…
Because I did for some reason use key => value syntax whenever I used foreach to loop over associative arrays.

I guess because indeed in most cases when you loop over an associative array, the keys will have some use.

I realize now that’s just plain unnecessary, unless one wants explicitly the keys assigned to $key - which in this use case I don’t need.

I didn’t see the tree in the forest I guess.

Thanks, the issue is clearly my code 🫣

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.