Newsgroups: php.internals Path: news.php.net Xref: news.php.net php.internals:45863 Return-Path: Mailing-List: contact internals-help@lists.php.net; run by ezmlm Delivered-To: mailing list internals@lists.php.net Received: (qmail 60425 invoked from network); 22 Oct 2009 01:40:32 -0000 Received: from unknown (HELO lists.php.net) (127.0.0.1) by localhost with SMTP; 22 Oct 2009 01:40:32 -0000 Authentication-Results: pb1.pair.com smtp.mail=jille@hexon.cx; spf=permerror; sender-id=unknown Authentication-Results: pb1.pair.com header.from=jille@hexon.cx; sender-id=unknown Received-SPF: error (pb1.pair.com: domain hexon.cx from 85.223.64.56 cause and error) X-PHP-List-Original-Sender: jille@hexon.cx X-Host-Fingerprint: 85.223.64.56 56-64-223.ftth.xms.internl.net Received: from [85.223.64.56] ([85.223.64.56:41311] helo=istud.quis.cx) by pb1.pair.com (ecelerity 2.1.1.9-wez r(12769M)) with ESMTP id C4/E2-44649-E08BFDA4 for ; Wed, 21 Oct 2009 21:40:31 -0400 Received: from [192.168.0.4] (unknown [192.168.0.4]) by istud.quis.cx (Postfix) with ESMTP id B7078610920; Thu, 22 Oct 2009 03:40:27 +0200 (CEST) Message-ID: <4ADFB80B.9050207@hexon.cx> Date: Thu, 22 Oct 2009 03:40:27 +0200 User-Agent: Thunderbird 2.0.0.23 (Windows/20090812) MIME-Version: 1.0 To: Richard K Miller CC: internals@lists.php.net References: <84898698-728C-44ED-BF7A-E0E02C111F68@gmail.com> In-Reply-To: <84898698-728C-44ED-BF7A-E0E02C111F68@gmail.com> Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Subject: Re: [PHP-DEV] bug when using foreach with references? From: jille@hexon.cx (Jille Timmermans) Richard K Miller schreef: > Is this a bug in PHP? No > > $items = array('apple', 'banana', 'carrot'); > print_r($items); > foreach ($items as &$item) { } $item is now a reference to the last element of $items. > print_r($items); > foreach ($items as $item) { } And here, the foreach loop writes to $item for each element: thus assiging that value to the last element of $items. > print_r($items); > ?> > > // Output: > Array > ( > [0] => apple > [1] => banana > [2] => carrot > ) > Array > ( > [0] => apple > [1] => banana > [2] => carrot > ) > Array > ( > [0] => apple > [1] => banana > [2] => banana > ) > > Two bananas in the last set?! Not what I expected. You can fix your bug by using 'unset($item);' after the second foreach-loop. -- Jille > > Richard > >