Well, one difference is that each()
will only work on arrays (well only work right). foreach
will work on any object that implements the traversable
interface (Which of course includes the built in array type).
There may be a micro-optimization in the foreach. Basically, foreach is equivilant to the following:
$array->rewind();
while ($array->valid()) {
$key = $array->key();
$value = $array->current();
// Do your code here
$array->next();
}
Whereas each
basically does the following:
$return = $array->valid() ? array($array->key(), $array->current()) : false;
$array->next();
return $return;
So three lines are the same for both. They are both very similar. There may be some micro-optimizations in that each
doesn't need to worry about the traversable
interface... But that's going to be minor at best. But it's also going to be offset by doing the boolean cast and check in php code vs foreach
's compiled C... Not to mention that in your while/each
code, you're calling two language constructs and one function, whereas with foreach
it's a single language construct...
Not to mention that foreach
is MUCH more readable IMHO... So easier to read, and more flexible means that -to me- foreach
is the clear winner. (that's not to say that each
doesn't have its uses, but personally I've never needed it)...