monkey_05_06 Posted April 5, 2009 Share Posted April 5, 2009 Hey freaks, long time no see. Not that I was ever very active anyway... So basically I'm doing this: <?php echo "before foreach: " . $sets[4]["scriptName"] . "<br />\n"; foreach ($sets as $set) { echo "before: " . $sets[4]["scriptName"] . "<br />\n"; ?> <input type = "checkbox" name = "include_<?php echo $set["scriptName"]; ?>" <?php $checked = TRUE; if (!isset($_POST["include_{$set["scriptName"]}"])) $checked = FALSE; $query = "UPDATE `users` SET `include_{$set["scriptName"]}` = \"" . (($checked) ? "1" : "0") . "\" WHERE `UID` = \"{$userID}\""; @mysql_query($query); if ($checked) echo "checked "; ?>/> Include <?php echo $set["friendlyName"]; ?>?<br /> <?php if ($checked) print_set($set); echo "after: " . $sets[4]["scriptName"] . "<br />\n"; } ?> And the output I'm getting is very worrying to me. The echo prior to the foreach statement prints the proper value. However as soon as the first "before" statement is being printed, $sets[4]["scriptName"] is immediately set equivalent to $set["scriptName"]. This happens every loop, meaning that by the time it reaches $sets[4], the last index that $sets[4]["scriptName"] is now reading as $sets[3]["scriptName"]. Why is foreach doing this? I've never encountered this before, and as I said it happens immediately when the foreach block is entered. Just in case you were wondering, my print_set function doesn't have any access to the global $sets array, it only takes the parameter for the set to print out. Link to comment https://forums.phpfreaks.com/topic/152678-foreach-replacing-last-element-with-current/ Share on other sites More sharing options...
monkey_05_06 Posted April 6, 2009 Author Share Posted April 6, 2009 Update: I tried just using a for loop instead: for ($i = 0, $set = $sets[$i]; $i < count($sets); $i++, $set = (($i < count($sets)) ? $sets[$i] : NULL)) { It produced exactly the same results. Why? What in processing this command is causing the $sets array to be modified? Edit: Update Mark II - SOLVED! I was being an idiot. In a <b>PRIOR</b> foreach loop I was doing this: <?php foreach ($sets as &$set) { // ... } ?> So $set was still set as a reference to $sets[4]. D'oh! Simply calling unset($set); after I was done with using it by reference resolved the issue! Link to comment https://forums.phpfreaks.com/topic/152678-foreach-replacing-last-element-with-current/#findComment-802058 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.