Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Iterator::current — read the current value

Read the value at an iterator’s current position without advancing it. Use `valid()` to check the position so that `null` and `false` are not mistaken for the end of iteration.

Version: PHP 8.3

Syntax

public function current(): mixed; // declaration inside an interface
$value = $iterator->current(); // call on an Iterator instance

Iterator::current is a public instance method that takes no arguments and returns the value at the iterator’s current position. The mixed return type allows any PHP value, including null and false. Calling $iterator->current() does not advance the iterator: next() moves it forward, while key() reads the key instead of the value.

When traversing manually from the start, call rewind(), then use valid() after rewinding and after each next() before reading a value. If valid() returns false, skip current(): the interface does not specify a result for an invalid position. Do not test for the end by converting the value to bool or comparing it with null or false.

In an ordinary foreach loop over an Iterator, PHP calls rewind() at the start and checks valid() before reading the value through current(). The form foreach ($iterator as $key => $value) also reads the key through key(). If the loop continues to the next iteration, PHP calls next() and checks the position again.

Do not confuse the method with the global function \current($array), which reads the element at an array’s internal pointer. Passing an object to that function has been deprecated since PHP 8.1 and is not a substitute for calling the iterator method.

Examples

<?php
$iterator = new \ArrayIterator(['a' => null, 'b' => false]);

for ($iterator->rewind(); $iterator->valid(); $iterator->next()) {
    $value = $iterator->current();
    printf("%s: %s\n", $iterator->key(), var_export($value, true));
}

Result

a: NULL
b: false

This example requires no optional extension: `Iterator` is built into PHP 8.3, and SPL cannot be disabled in that version. The SPL class `\ArrayIterator` visits the two array entries in insertion order. `var_export($value, true)` produces the text `NULL` or `false`, so both values are visible. The loop stops when `valid()` returns `false`, not when the value read is `false`.

Related lessons

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

Sources