PHP foreach that returns keys only

You could do something like this

foreach(array_keys($array) as $key) {
 // do your stuff
}

That would make the foreach iterate over an array consisting of the keys from your array instead of the actual array. Note that it's probably not better from a performance standpoint though.


Just ignore this message.

In PHP the way you used foreach is the fastest. It is right, that you should avoid unused variables, but in this case you cannot avoid it, without losing some performance.

E.g. foreach(array_keys($arr) as $key) is about 50% to 60% slower
than foreach($arr as $key => $notUsed).

This issue of phpmd is already reported here and there is also already a pull request here.

Until phpmd is updated you can also use this little hack

In the file /src/main/php/PHPMD/Rule/UnusedLocalVariable.php in the method collectVariables(..) (line 123 in my case) replace

if ($this->isLocal($variable))

by

if ($this->isLocal($variable) && !($this->isChildOf($variable, 'ForeachStatement') && $variable->getName() === '$notUsed'))

This will stop phpmd from reporting $notUsed anywhere inside a foreach loops.

UPDATE: The recommendation above assumes PHP 5.6 (the relevant version at the time of writing this answer). But time went by and now using PHP 7.2 it seems to be the other way around. As always it depends on the exact use case, but for associative arrays with less than 100.000 keys it is faster to store array_keys($arr) in a variable and use this in a foreach loop.