Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Iterator::key — Read the current element’s key

Read the current element’s key without advancing the iterator, and see how PHP assigns that key in a `foreach` loop.

Version: PHP 8.3

Syntax

public function key(): mixed

$iterator->key();

Iterator::key is a public instance method with no parameters. Call $iterator->key() to read the key at the current position without moving the iterator. current() reads the value at that same position, next() advances, and rewind() returns to the start.

In foreach ($iterator as $key => $value), PHP calls rewind() at the start and checks valid() before each iteration. At a valid position it reads the value with current() and the key with key(). It calls next() after a normal pass through the loop body. When iterating manually, check valid() rather than testing the key: 0 can be a valid key.

The mixed return type does not restrict keys to int and string: for example, MultipleIterator::key() returns an array. ArrayIterator::key() has a narrower signature: string|int|null. The interface manual describes null and E_NOTICE on failure, but do not assume every implementation behaves that way at an invalid position. In PHP 8.3, declare public function key(): mixed or a compatible narrower return type in your own implementation to avoid a signature deprecation notice.

Do not confuse the method with the global \key($array) function, which returns the key of the element at the array’s internal pointer. Passing an object to that function has been deprecated since PHP 8.1.

Examples

<?php
$iterator = new \ArrayIterator([0 => 'oak', 'tree' => 'pine']);

$iterator->rewind();
if ($iterator->valid()) {
    echo $iterator->key(), ', ', $iterator->key(), "\n";
}

$iterator->next();
if ($iterator->valid()) {
    echo $iterator->key(), "\n";
}

foreach ($iterator as $key => $value) {
    echo $key, ' => ', $value, "\n";
}

Result

0, 0
tree
0 => oak
tree => pine

The example uses SPL’s `\ArrayIterator`. Two reads both return `0`; `next()` moves the iterator to `tree`. The `foreach` loop starts from the beginning and prints both pairs.

Related lessons

  • PHP · Lesson 61 · Advanced · Version: 2
  • PHP · Lesson 63 · Advanced · Version: 2

Sources