<?php
function hasValues(iterable &$value): bool {
if (is_array($value)) {
return (bool)$value;
}
if ($value instanceof \Iterator) {
return $value->valid();
}
$value = $value->getIterator();
return hasValues($value);
}
$weakMap = new WeakMap();
$x = new stdClass();
$y = new stdClass();
$weakMap[$x] = 'x';
$weakMap[$y] = 'y';
$data = [
[1, 2, 3],
[],
(fn () => yield from [1, 2, 3])(),
(fn () => yield from [])(),
new ArrayIterator([1, 2, 3]),
new ArrayIterator([]),
$weakMap,
new WeakMap(),
new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/tmp', RecursiveDirectoryIterator::SKIP_DOTS)),
];
foreach ($data as $d) {
print_r([
'value' => $d,
'hasValues' => var_export($hasValues = hasValues($d), true),
// Once a generator is checked and does not have any values we can't attempt to iterate it anymore.
'values' => $hasValues ? (is_array($d) ? $d : iterator_to_array($d, false)) : 'null',
]);
}
preferences:
24.53 ms | 406 KiB | 5 Q