smileBeda
(Beda Schmid)
1
- 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
None, other than breaking my code or using the $key for some needless operation?
What do I miss?
ganncamp
(G Ann Campbell)
2
Hi,
Are you using SonarCloud or SonarQube? And if the latter, which version?
Â
Thx,
Ann
smileBeda
(Beda Schmid)
3
SonarCloud
I had posted this initially in that “help” forum but it was moved, sorry.
ganncamp
(G Ann Campbell)
4
Hi,
Thanks. This is flagged for more expert attention. Hopefully, they’ll be along soon.
Â
Ann
1 Like
pynicolas
(Pierre-Yves Nicolas)
5
Hi,
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 ) {
...
}
2 Likes
smileBeda
(Beda Schmid)
6
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
system
(system)
Closed
7
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.