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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.