Array cursor.
Moderator: General Moderators
Array cursor.
What does this page mean by "Advances the array cursor"? What's the array cursor?
Re: 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 ...JellyFish wrote:What does this page mean by "Advances the array cursor"? What's the array cursor?
Code: Select all
while (list($key, $val) = each($fruit)) {
echo "$key => $val ";
}It is very similar to C's concept ofpointer arithmetic.
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.
Anyway, this allows you to iterate through an array without using a function such as foreach.
So basically, if I write:
$v1 would equal to the second index in $array?
Code: Select all
$v1 = each($array);
$v2 = each($array);
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 1Okay, well I have another question.
If I looped through the array with:
which index in $array would the last statement output? In other words where would the array cursor be?
If I looped through the array with:
Code: Select all
while (each($array))
{
}
//then use each for for the same array
echo each($array);
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";