PHP foreach that returns keys only

前端 未结 7 850
逝去的感伤
逝去的感伤 2020-12-29 18:51

Theoretical question that perhaps does not make any sense but still, maybe there is a clever answer.

I want to iterate through array and get its keys and to somethin

7条回答
  •  独厮守ぢ
    2020-12-29 19:11

    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.

提交回复
热议问题