reset: to move the cursor to first element of an array

The internal pointer of a PHP array or cursor moves by pointing from first to last element or can move beyond last element. We can bring the pointer to first element by using reset().
Example
$my_array=array("First One", "Second One", "Third One", "Fourth One", "Fifth One");
while (list ($key, $val) = each ($my_array)) { 
echo "$key -> $val <br>"; 
}
// Now the pointer has moved beyond the last element of the array //
reset($my_array); // Moves the pointer to first element
echo current($my_array); // Output is First One
In the above code we have used one while loop and used each function to display elements. After execution of the while loop the internal pointer will move beyond the last element of the array. We can use current() to know the status of the pointer. It will return FALSE if the pointer is beyond the last element.
Example :
$my_array=array("First One", "Second One", "Third One", "Fourth One", "Fifth One");
while (list ($key, $val) = each ($my_array)) { 
echo "$key -> $val <br>"; 
}
//reset($my_array); // Moves the pointer to first element

if(current($my_array)){
echo " Current value : ".current($my_array);
}else{
echo "The pointer moved beyond last element or the array is empty ";
}
In above example we have not used the reset() function by commenting the line, so internal pointer will move beyond the last element and the current() function will return FALSE.

We will use the next & previous (prev) commands to move the array in different direction.
$my_array=array("First One", "Second One", "Third One", "Fourth One", "Fifth One");
while (list ($key, $val) = each ($my_array)) { 
echo "$key -> $val <br>"; 
}
reset($my_array); // Moves the pointer to first element
next($my_array); // MOves the pointer to second element
if(current($my_array)){
echo " Current value : ".current($my_array);
}else{
echo "The pointer moved beyond last element or the array is empty ";
}
To know the present position of the cursor we will use current() function.
$my_array=array("First One", "Second One", "Third One", "Fourth One", "Fifth One");

echo current($my_array); // Output : First One 
echo next($my_array); // Output : Second One 
echo next($my_array); // Output : Third One 
echo prev($my_array); // Output : Second One 
echo end($my_array); // Output : Fifth One 
echo reset($my_array); // Output : First One

Subscribe to our mailing list

* indicates required
Subscribe to plus2net
Your Rating


Google+

Post Comment This is for short comments only. Use the forum for more discussions.




Subscribe to our mailing list

* indicates required
Subscribe to plus2net
HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us
©2000-2018 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer