Last updated: December 3, 2026.
If a PHP iterable must yield exactly one value, count the values during traversal. Converting a keyed generator into an array can overwrite earlier values when the same key appears more than once.
<?php
function exactlyOne(iterable $values): mixed
{
$seen = false;
$result = null;
foreach ($values as $value) {
if ($seen) {
throw new UnexpectedValueException('More than one result');
}
$result = $value;
$seen = true;
}
if (!$seen) {
throw new UnexpectedValueException('No results');
}
return $result;
}
echo exactlyOne(['ready']), PHP_EOL;Count yielded items independently of their keys
The helper stops as soon as it observes a second value. It keeps one candidate in memory and does not need a separate counting pass. This matters when the source is a generator that cannot be rewound once consumed, or when collecting the entire result would be expensive.
A separate flag distinguishes an empty sequence from a sequence containing one null. It also lets zero, false and empty strings pass as legitimate single values. Test an empty input, one null and two values yielded with the same key. The last case should be rejected even though both values have the same label.
Choose the right check for collections and database queries
If you actually need a full array and can drop the original keys, pass false as the second argument to iterator_to_array(). PHP will preserve every yielded value under numeric keys. This materializes the whole result and is unnecessary when you only care whether a second item exists.
If the source is a database query and you control it, fetch at most two matching rows using the engine’s row-limit syntax. One row establishes success, and two are enough to detect an ambiguous result. Add a database uniqueness constraint when the rule should hold across writes instead of relying only on a reader check.