Cycling Through PHP Arrays using Pointers

PHP

Cycling Through PHP Arrays

When accessing the values of PHP arrays, looping them through foreach loops is not the only way. We can get individual values and keys of an array. There are invisible pointers in an array that tells the current position. We can cycle through them to get values at different positions of an array. We use current(), next(), prev(), end(), reset() and each() functions for cycling through the values/positions.

Here’s what those functions do:

current(): Access the value of the current array position.
next(): Move the invisible array pointer to the next position and access it as well.
prev(): Move the invisible array pointer to the previous position and access it.
end(): Move the invisible array pointer to the end of the array and access it.
reset(): Reset the array pointer i.e. move the pointer to the first array value and access the value.
each(): Access the current key as well as value of an array. The pointer is moved forward after they are accessed.

Example use of these statements to move the array pointers while printing them

<?php
$values = array("Value 1", "Value 2", "Value 3", "Value 4", "Value 5");
echo current($values); //Value 1
echo "<br />";
echo next($values); //Value 2
echo "<br />";
echo prev($values); //Value 1
echo "<br />";
echo end($values); //Value 5
echo "<br />";
echo reset($values); //Value 1
echo "<br />";
echo current($values); //Value 1
echo "<br />";
next($values);
next($values);
echo current($values); //Value 3
echo "<br />";
prev($values);
prev($values);
echo current($values); //Value 1
?>
Output:
Value 1
Value 2
Value 1
Value 5
Value 1
Value 1
Value 3
Value 1

each() function

This function is quite useful for looping through and accessing all the values one by one. The result of each function is stored as an array.

Here’s what each() does:

<?php
$arr = array("One", "Two", "Three", "Four", "Five");
$access = each($arr);
print_r($access);
echo "<br />";
$access = each($arr);
print_r($access);
?>
Output:
Array ( [1] => One [value] => One [0] => 0 [key] => 0 )
Array ( [1] => Two [value] => Two [0] => 1 [key] => 1 )

This function is used with list function to cycle through and access all the values of an array. Here’s how you do it:

<?php
$arr = array("One", "Two", "Three", "Four", "Five");
while(list($key,$value)=each($arr))
{
echo $key." : ".$value;
echo "<br />";
}
?>
Output:
0 : One
1 : Two
2 : Three
3 : Four
4 : Five