PHP 8.4.6 Released!

ArrayIterator::seek

(PHP 5, PHP 7, PHP 8)

ArrayIterator::seekSeeks to a position

Açıklama

public ArrayIterator::seek(int $offset): void

Seeks to a given position in the iterator.

Bağımsız Değişkenler

offset

The position to seek to.

Dönen Değerler

Hiçbir değer dönmez.

Hatalar/İstisnalar

Throws an OutOfBoundsException if the offset is not seekable.

add a note

User Contributed Notes 2 notes

up
6
jon at ngsthings dot com
16 years ago
<?php
/ didn't see any code demos...here's one from an app I'm working on

$array = array('1' => 'one',
'2' => 'two',
'3' => 'three');

$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();

if(
$iterator->valid()){
$iterator->seek(1); / expected: two, output: two
echo $iterator->current(); / two
}

?>
up
4
foalford at gmail dot com
8 years ago
<?php
/seek alter the iterator's internal indice instead of the value that key() returns.
/This is a big trap if combining with uasort/natsort function.

$a = new ArrayObject([4,3,2,1]);
$it = $a->getIterator();
$it->natsort(); /The Iterator preserve the key while sorting the array
$it->rewind();
$first = $it->key(); /The first element is 1 and it's key is 3
echo $first. PHP_EOL; / 3

$it->next();
$second = $it->key();
echo
$second. PHP_EOL; /2

$it->next();
$it->seek($first); /Was intended to seek to element 1, key 3, indice 0
echo $it->key() . PHP_EOL; /end up 0 because seek took parameter as indice instead of key. It seek to element indice 3, element 4 key 0.

var_dump($it);

/* Output:
3
2
0
object(ArrayIterator)#2 (1) {
["storage":"ArrayIterator":private]=>
object(ArrayObject)#1 (1) {
["storage":"ArrayObject":private]=>
array(4) {
[3]=>
int(1)
[2]=>
int(2)
[1]=>
int(3)
[0]=>
int(4)
}
}
}
*/
To Top

Follow Lee on X/Twitter - Father, Husband, Serial builder creating AI, crypto, games & web tools. We are friends :) AI Will Come To Life!

Check out: eBank.nz (Art Generator) | Netwrck.com (AI Tools) | Text-Generator.io (AI API) | BitBank.nz (Crypto AI) | ReadingTime (Kids Reading) | RewordGame | BigMultiplayerChess | WebFiddle | How.nz | Helix AI Assistant