Anonymous array with foreach loop in PHP
I was wondering how PHP handles an anonymous array, if I make use of it like this:
foreach(array('a', 'b') as $foo) {
// ...
}
This wouldn't work if the array gets recreated on every step - but it works, so it looks like PHP creates a variable for that array (or something similar, doesn't really matter) - meaning this wouldn't actually have a bad perfomance. But is there any point why not to use anonymous arrays with foreach loops? (it kinda "loo开发者_如何学Goks wrong/bad" to me)
I don't see a reason not to use this.
It doesn't matter whether you use a directly initialized array, or an array variable as an argument for foreach
. They're both valid arguments and there is no reason to assume that an anonymous array is handled any differently.
From a code maintenance perspective, it's also perfectly clear what is being done here, so there are no legibility issues either.
That's a perfectly normal array, and such, should work.
Your terminology is quite weird, the term anonymous makes sense for functions, because normally the have names, but for arrays? Is an integer anonymous if you don't directly assign it to a variable? :) Nah..
精彩评论