Jump to content

[SOLVED] How to use an array twice?


0x00

Recommended Posts

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

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>";
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.