PHP 8.2 changes to iterator functions I missed

Jul 30, 2024·
Gert de Pagter
Gert de Pagter
· 1 min read

This week I learned of a small change that got introduced in PHP 8.2 that I completely missed. The iterator_*() functions got an update, which make them actually usable when dealing with the iterable type. Now this is only really relevant if you are dealing with iterables that might not be arrays, but you need to use them as an array.

The big change is that a function like iterator_to_array, it now accepts the iterable type, rather than just \Traversable. For some code I’m working on it means I can refactor a lot of code to remove is_array checks all over the place.

// Pre PHP 8.2:
function getAllStringLengths(iterable $input): array {
  if(!is_array($input)) {
    $input = iterator_to_array($input);
  }
  
  return array_map(strlen(...), $input);
}

// Post PHP 8.2
function getAllStringLengths(iterable $input): array {
  return array_map(strlen(...), iterator_to_array($input));
}

If you want to get notified of the next blog post, join the newsletter.