0x00 Posted October 30, 2007 Share Posted October 30, 2007 In the following example, why can you not iterate through the array twice, yet still access it directly later? <?php $data = array(); $data['one'] = 1; $data['two'] = 2; $data['three'] = 3; while (list($k, $v) = each($data)) { echo "".$k.": ".$v."<br>"; } echo "<br><br><br>"; while (list($k, $v) = each($data)) { echo "".$k.": ".$v."<br>"; } echo "<br><br><br>"; echo "one: ".$data['one']."<br>"; ?> Link to comment https://forums.phpfreaks.com/topic/75346-solved-how-to-use-an-array-twice/ Share on other sites More sharing options...
Rithiur Posted October 30, 2007 Share Posted October 30, 2007 Arrays have internal pointers, which the function each() uses. Once the first loop has run through, the internal pointer will be at the end of the array, Thus, the second loop wont print anything because the pointer is already at the end and each() can't advance it. To reset the pointer to the beginning, you can use reset() function, like reset($data); before the next each() loop. You could also use the foreach loop like "foreach ($data as $k => $v)", because foreach operates on a copy of the array so it doesn't advance the arrays internal pointer. So, you could for example use this: <?php $data = array(); $data['one'] = 1; $data['two'] = 2; $data['three'] = 3; foreach ($data as $k => $v) { echo "".$k.": ".$v."<br>"; } echo "<br><br><br>"; foreach ($data as $k => $v) { echo "".$k.": ".$v."<br>"; } echo "<br><br><br>"; echo "one: ".$data['one']."<br>"; ?> Link to comment https://forums.phpfreaks.com/topic/75346-solved-how-to-use-an-array-twice/#findComment-381056 Share on other sites More sharing options...
0x00 Posted October 30, 2007 Author Share Posted October 30, 2007 Top banana, makes sense that does arh! Cheers! Link to comment https://forums.phpfreaks.com/topic/75346-solved-how-to-use-an-array-twice/#findComment-381058 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.