PHP Array Cursors

I don’t recommend ever using these functions because a foreach loop is so much simpler and shorter. The only reason I’m writing about these is bacause I have almost never used them and they may just be on the Zend PHP Certification exam.

There are a number of functions designed specifically for manipulating array pointers. Most examples that I’ve seen use these functions during some sort of array iteration. When starting an iteration over an array, the first step is usually to reset the pointer to its initial position using the reset() function. After that, moving forward or backwards by one position is done using prev() and next(). At any given point, we can access the value of the current element using current() and its key using key(). Here’s a simple example:

  1.  
  2. $array = array(’foo’ => ’bar’, ’baz’, ’bat’ => 2);
  3. function displayArray($array) {
  4.         reset($array);
  5.         while (key($array) !== null) {
  6.                 echo key($array) .": " .current($array) . PHP_EOL;
  7.                 next($array);
  8.         }
  9. }
  10.  

The displayArray function above will display all the values in an array. Reset() is called first to return the internal array pointer to the first element. Next, using a while loop, the current key and value is displayed using the key() and current() functions. Finally, the array pointer is advanced, using next().

Since you can iterate back-and-forth within an array by using its pointer, you could—in theory—start your iteration from the last element (using the end() function to reset the pointer to the bottom of the array) and then making your way to the beginning:

  1.  
  2. $a = array (1, 2, 3);
  3. end($a);
  4. while (key ($array) !== null) {
  5.         echo key($array) .": " .current($array) . PHP_EOL;
  6.         prev($array);
  7. }
  8.  

So I guess that last example may be useful…but it’s still probably easier to reverse the entire array and use a foreach.

Anyway, if these are on the Zend PHP Certification exam, I shouldn’t have a problem.