note 73218 rejected from control-structures.foreach by bobby

From: Date: Wed, 14 Mar 2007 22:37:33 +0000
Subject: note 73218 rejected from control-structures.foreach by bobby
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-124460@lists.php.net to get a copy of this message
Note Submitter: nickw at telus dot net ---- Hi everyone. I've run into an interesting issue with foreach and I was wondering if anybody has experienced anything similar or if anybody can suggest what may be causing the problem. I have built up an array with the following structure: Array ( [1000128] => Array ( [month] => Array ( [signups] => 1 [conversionRatio] => 100 ) [day] => Array ( [conversionRatio] => 0 ) [week] => Array ( [conversionRatio] => 0 ) [name] => User 1 (1000128) ) [1000132] => Array ( [month] => Array ( [signups] => 1 [conversionRatio] => 100 ) [day] => Array ( [conversionRatio] => 0 ) [week] => Array ( [conversionRatio] => 0 ) [name] => User 2 (1000132) ) [1000142] => Array ( [month] => Array ( [signups] => 2 [conversionRatio] => 100 ) [day] => Array ( [conversionRatio] => 0 ) [week] => Array ( [conversionRatio] => 0 ) [name] => User 3 (1000142) ) ) I then use uasort() to sort the array and array_reverse() to put the sort in descending order. Finally, I use foreach to iterate through this array to display the results in a simple HTML table. The problem is that the iteration is duplicating one of the records seemingly at random. For instance, instead of seeing: User 3: signups=2 conversionRatio=100% User 1: signups=1 conversionRatio=100% User 2: signups=1 conversionRatio=100% as expected, I get User 3: signups=2 conversionRatio=100% User 1: signups=1 conversionRatio=100% User 1: signups=1 conversionRatio=100% When I print the array using print_r just prior to the foreach loop, everything seems to be in order. At first, I thought there might be some issue with the internal pointer so I've tried using reset(), and also tried removing the calls to uasort() and array_reverse(). The same problem appears, just with different records being duplicated each time. I've checked the value of $id within the foreach (I use the line foreach ($arr as $id => $values)) and each id is being printed in turn but the $value portion (in this case corresponding to 1000142) appears to be overwritten with the previous $value array. As a temporary workaround, I've gone to using foreach (array_keys($arr) as $id) and then pulling individual values by using $arr[$id][...] and this is working as expected. However, I would obviously like to avoid this hack as I do use foreach quite extensively in other scripts and the appearance of this problem is quite unsettling. Any feedback will be greatly appreciated. Thanks!

« previous php.notes (#124460) next »