Page 1 of 1

Array cursor.

Posted: Tue Aug 07, 2007 8:23 pm
by JellyFish
What does this page mean by "Advances the array cursor"? What's the array cursor?

Re: Array cursor.

Posted: Tue Aug 07, 2007 8:39 pm
by ev0l
JellyFish wrote:What does this page mean by "Advances the array cursor"? What's the array cursor?
The array cursor is an internal pointer that points to an element in an array. The current function will fetch the "current" element in an array that the array cursor points to. This pointer is stored as part of the array internally within PHP. It is useful for looping through an array. Before PHP had the foreach a common way to look through an array was by using while like soo ...

Code: Select all

while (list($key, $val) = each($fruit)) {
    echo "$key => $val ";
}


It is very similar to C's concept ofpointer arithmetic.

Posted: Tue Aug 07, 2007 9:11 pm
by Benjamin
So your array has 5 elements. The internal pointer is pointed at the first one (0). You pull one out using each, now it's pointing at the second element (1). Element 0 still exists. You can use the PHP function reset to reset the cursor. I call it a pointer though. Without looking I don't know what the correct term is. It sounds like both are used interchangeably.

Anyway, this allows you to iterate through an array without using a function such as foreach.

Posted: Tue Aug 07, 2007 9:22 pm
by JellyFish
So basically, if I write:

Code: Select all

$v1 = each($array);
$v2 = each($array);
$v1 would equal to the second index in $array?

Posted: Tue Aug 07, 2007 11:48 pm
by Benjamin
Like this..

Code: Select all

$x = array(1, 2, 3);

list(, $value) = each($x);
echo $value;  // would echo 1

list(, $value) = each($x);
echo $value; // would echo 2

reset($x);

list(, $value) = each($x);
echo $value; // would echo 1

Posted: Wed Aug 08, 2007 1:03 am
by JellyFish
K cool. Now I understand.

But does each array get it's own array cursor?

Posted: Wed Aug 08, 2007 1:06 am
by Benjamin
JellyFish wrote:But does each array get it's own array cursor?
What do you mean?

Posted: Wed Aug 08, 2007 4:21 am
by volka
JellyFish wrote:But does each array get it's own array cursor?
Yes.

Posted: Wed Aug 08, 2007 7:41 pm
by JellyFish
Okay, well I have another question.

If I looped through the array with:

Code: Select all

while (each($array))
{

}
//then use each for for the same array
echo each($array);
which index in $array would the last statement output? In other words where would the array cursor be?

Posted: Wed Aug 08, 2007 8:00 pm
by volka
Why not try it?

Code: Select all

<?php
echo "<pre>\n";
$arr = array('a', 'b', 'c');
while ( $e=each($arr) ) {
	var_dump($e);
}
echo "1---\n";
var_dump(each($arr));
echo "2---\n";
$arr[] = 'xyz';
var_dump(each($arr));
echo "</pre>\n";