CKTIS / PHP
Iterator::valid — Check the iterator’s current position
`Iterator::valid()` tells you whether there is an element at the iterator’s current position. It does not test the element’s value or advance the iterator.
Version: PHP 8.3
Syntax
public function valid(): boolIterator::valid() is an instance method with no arguments, called as $iterator->valid(). It returns true when the current position has an element and false when it does not. It does not advance the iterator. Values such as null, false, and 0 can all be valid elements.
When foreach uses the Iterator interface, PHP starts by calling rewind() and then valid(). If the result is true, the loop obtains the value with current() and, if needed, the key with key(). When the loop continues, next() advances the iterator and valid() checks the new position. A false result ends iteration without reading an element at that position. For an empty iterator, the first check returns false.
When iterating manually, check valid() before reading with current() or key(). If your implementation uses the position as a key in an array $items, use array_key_exists($position, $items) rather than isset($items[$position]): isset() also returns false for an existing key whose value is null.
In PHP 8.3, Iterator is a built-in interface, and ArrayIterator is provided by SPL, which cannot be disabled.
Examples
<?php
$iterator = new ArrayIterator([null, false, 0]);
for ($iterator->rewind(); $iterator->valid(); $iterator->next()) {
var_dump($iterator->current());
}
var_dump($iterator->valid());
Result
NULL bool(false) int(0) bool(false)
The first three lines are element values returned by `current()`. The second line, `bool(false)`, is an element value; only the last `bool(false)` comes from `valid()` and means there is no element at the current position.
Related lessons
- PHP · Lesson 61 · Advanced · Version: 2
- PHP · Lesson 63 · Advanced · Version: 2