>> Is this a bug in PHP? >> > After the first foreach loop, wher $item was set by reference, $item > is still set (by reference) after you exit the loop. (There is no > special scope for inside a foreach loop, so &$item is set in the > global scope.) > When the next foreach loop sets $item, it was still set by > reference, so it is probably overwriting that location as it sets > $item the second time. > > I think the docs on foreach (or on references or iterators) make > mention of weird things that can happen when you do a foreach by > reference or when you change the array you're iterating through. >
Mac, you're right about the foreach() docs mentioning it. There are at least 8 comments that talk about it, though most take the approach of "here's how to get around this funny foreach() behavior." For me it was helpful to consider this code. When you understand why this outputs "bananabanana", the foreach() bug starts to make more sense: <?php $a = "apple"; $b = &$a; $b = "banana"; echo $a; echo $b; ?> However, that's not to say it was intuitive. If you build an e- commerce site and notice that users constantly double-click the Submit button, causing two orders to be submitted, you have at least 2 options: 1. Put a large, pink warning box above the shopping cart, telling users not to double-click the Submit button. Mention it repeatedly in your documentation. When users see two charges on their credit card and call your customer service department, tell them they must not have read the documentation. Tell them you can't change the shopping cart because 0.01% of your users might actually want to submit two orders via a double-click, or three orders via a triple-click. Begrudgingly refund the second charge on their credit card. Make them question why they use your site instead of your competitors'. Forget that it might actually be less work for you to make the change instead of continuing to support it. OR 2. Add a few lines of JavaScript code to hide the Submit button after it's been clicked once. Watch for closely spaced double orders on the backend. We all have moments as the user and moments as the seller. Proper design is about abstracting the complexity away from your users and not requiring them to think as deeply about internals as you had to. </soapbox> _______________________________________________ UPHPU mailing list [email protected] http://uphpu.org/mailman/listinfo/uphpu IRC: #uphpu on irc.freenode.net
