Jump to content

why key($myArray) does not return key inside " For Each " Loop ??


lostnucleus

Recommended Posts

Well that's interesting.

 

No, actually not. key() does not advance the internal array pointer. And the 111 is due to his code, not the above example. Which outputs 000

 

$data = array('cat','bat','rat','net');
echo key($data), '<br/>';

foreach($data as $key => $value)
{
echo 'key(): ', key($data), ' $key: ', $key, '<br/>';
}

 

Outputs:

 

0<br/>
key(): 1 $key: 0<br/>
key(): 1 $key: 1<br/>
key(): 1 $key: 2<br/>
key(): 1 $key: 3<br/>

 

foreach() advances the array pointer by 1?

Link to comment
Share on other sites

On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one...

 

...When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array...

 

...foreach operates on a copy of the specified array and not the array itself

 

Then why is the original array internal pointer advanced by one?

Link to comment
Share on other sites

On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one...

 

...When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array...

 

...foreach operates on a copy of the specified array and not the array itself

 

Then why is the original array internal pointer advanced by one?

 

That Q is killing me , why this is happening ???

 

 

Link to comment
Share on other sites

The discrete array functions that modify or access an array pointer - end(), key(), each(), prev(), reset(), next(), ... cannot be used inside of a foreach() loop to access the same array that is being iterated over. There is no need to do so or you should not be using a foreach() loop in the first place.

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.