The fix for this is that foreach should create a new iterator variable which overwrites the existing one. That would preserve expected behavior.
I think you should pause for a minute and summarize all of the WTFs you've rationalized on this post. Just the volume of it makes me incredulous that you don't think PHP == FAIL (or perhaps === if you like).
> The fix for this is that foreach should create a new iterator variable which overwrites the existing one.
That would be very strange behavior though that has no equivalence in any other part of the language. I'm sure if it did that, somebody would put on the list of things that PHP does weirdly!
> That would preserve expected behavior.
I'm afraid the behavior it has is the expected behavior. The problem isn't the language in this case.
> Just the volume of it makes me incredulous that you don't think PHP == FAIL (or perhaps === if you like).
Clearly you haven't been paying attention to my posts. I might be rationalizing some of these sort of ridiculous ones but I certainly don't think PHP is full of win. I'm just pragmatic. These problems just aren't that bad.
> That would be very strange behavior though that has no equivalence in any other part of the language.
How is it strange? When you declare your iteration variable, it unsets any existing definition of that variable if there is one, before it inserts the new variable. Why would anyone enter a loop and expect the iteration variable to have a value defined outside the loop?
Moreover, even if someone can find a reason why -- why make define the language around a need to support such badly designed programs.
> I'm afraid the behavior it has is the expected behavior.
Fine. s/expected/intuitive/g
> The problem isn't the language in this case.
Agreed. It's the people who designed it.
> These problems just aren't that bad.
This is my point: the individual issues are all workable. The real problem is that the language is maintained by people who have no idea how to design a language, frankly.
> How is it strange? When you declare your iteration variable
You're not declaring anything; PHP doesn't have variable declarations. In this case, you're either creating a new variable or using an existing one -- just like everywhere else. But I'll concede the point. While the code is technically correct, unsetting the loop variable might be a nice addition. But I fully understand why they wouldn't want to make this change.
> Why would anyone enter a loop and expect the iteration variable to have a value defined outside the loop?
Thus us the takeaway point, I think. The loop would work perfectly fine if $bar was lexically scoped to the foreach, but it isn't. That's a general weakness in PHP compared to pretty much any other scripting language used today.
I think you should pause for a minute and summarize all of the WTFs you've rationalized on this post. Just the volume of it makes me incredulous that you don't think PHP == FAIL (or perhaps === if you like).