I was going through some third party code and I ran onto this snippet for going through an array. Since this is a respectful code base I'm wandering what is the secret behind the trouble of moving internal pointer versus using the good old foreach loop.
Thanks for your input!
$handlerKey = null;
reset($this->handlers);
while ($handler = current($this->handlers)) {
if ($handler->isHandling(array('level' => $level))) {
$handlerKey = key($this->handlers);
break;
}
next($this->handlers);
}
CodePudding user response:
The difference is that you are explicitly stating you want to move to the next value of the iterable as opposed to allowing PHP to do it for you.
This pattern of stating that you want to move to the next value is useful if you will conditionally execute further logic in your loop. But this can be accomplished with less code by simply using the continue()
statement. In this scenario, however, both are unnecessary.
Remember that PHP was originally designed as an API for the C language, in which the developer would directly manipulate memory stores and registers. This could be an old design pattern inherited from that.