public function testPointer() { $ary = \range(0, 19); $this->assertEquals(0, \r8\ary\pointer($ary)); end($ary); $this->assertEquals(19, \r8\ary\pointer($ary)); prev($ary); prev($ary); prev($ary); $this->assertEquals(16, \r8\ary\pointer($ary)); }
/** * Sets the internal array pointer to a specific offset * * @param Array $array The array to operate on * @param Integer $offset The offset to seek to * @param Integer $wrapFlag How to handle offsets outside the array range * @return Mixed Returns the value at the given offset. NULL will be returned * if the given array is empty */ function seek(array &$array, $offset, $wrapFlag = FALSE) { $count = count($array) - 1; if ($count == -1) { return NULL; } $offset = \r8\ary\calcOffset($array, $offset, $wrapFlag); // escape from the easy out if ($offset == 0) { return reset($array); } if ($offset == $count) { return end($array); } // Get the position of the current pointer $pointer = \r8\ary\pointer($array); // If we are already at our destination... if ($pointer == $offset) { return current($array); } // If the point we are seeking to is closer to the beginning than it is // to the end or to the current pointer position, seek from the start if ($offset < abs($pointer - $offset) && $offset < abs($count - $offset)) { reset($array); $pointer = 0; } else { if (abs($count - $offset) < abs($pointer - $offset)) { end($array); $pointer = $count; } } // If we are seeking backward if ($pointer > $offset) { // seek to the before final point for ($pointer--; $pointer >= $offset; $pointer--) { prev($array); } } else { // seek to the final point for ($pointer++; $pointer <= $offset; $pointer++) { next($array); } } return current($array); }