Categories
PHP

Array Internal Pointers

Along with the keys and the associated values stored in an array, PHP maintains an internal index that points to the current element in the array.

Several functions use and update this array index to provide access to elements in the array:

  1. current() or pos()
    Returns the value of the current element in an array.
  2. end()
    Sets the internal pointer of an array to its last element, and also returns the value of the element.
  3. reset()
    Sets the internal pointer of an array to its first element, and also returns the value of the element.
  4. next()
    Advances the internal array pointer of an array, and also returns the value of the element.
  5. prev()
    Rewinds the internal array pointer of an array, and returns its value.
  6. each() : (deprecated as of PHP 7.2.0 and remove as of PHP 8.0)
    returns the current key and value pair from an array and advances the array cursor.
  7. key()
    Fetches a key from the current element in an array.

To illustrate how this internal index can be used, consider the following example:

<?php
 $a = array("a", "b", "c", "d", "e", "f");

 echo current( $a ); // prints "a"

 echo next   ( $a ); // prints "b"
 echo current( $a ); // prints "b"

 echo prev   ( $a ); // prints "a"
 echo current( $a ); // prints "a"

 echo end    ( $a ); // prints "f"
 echo current( $a ); // prints "f"

 echo reset  ( $a ); // prints "a"
 echo current( $a ); // prints "a"

 echo key    ( $a ); // prints "0"
 next ( $a ); 
 echo key    ( $a ); // prints "1"

The internal index is set to point at the first element when a new array is created, and the function current( ) returns the value pointed to by the array’s internal index.

Before the foreach statement was introduced to the PHP language, a common way to iterate through an associative array was to use a while loop with the each( ) function to get the key/value pairs for each element and the list( ) function to assign these values to variables. The following example shows how such an iteration is performed:

<?php
 $sounds = array ("cow"=>"moo", "duck"=>"quack", "dog"=>"woof");
 while (list($animal, $sound) = each($sounds)) {
  echo "<p>A $animal sounds $sound.</p>";
 }

The foreach statement is clearer and should be used in most cases.


Working with arrays:

  1. Creating Arrays
  2. Array Iteration
  3. Array Internal Pointers
  4. Explode and Implode Functions
  5. Count Array Elements, Find Min and Max Values
  6. Search values and keys in arrays
  7. Filter array elements using array_filter()
  8. Modify array elements using array_map() and array_walk()
  9. Split, tokenize, and iterate a string
  10. Convert a delimited string into an array
  11. Sorting arrays