Skip to content

50: Replace Deprecated ArrayIterator Methods

Sort the backing collection before creating its iterator. PHP 8.6 deprecates ArrayIterator’s sorting, flag access, and legacy serialization methods.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable arrayiterator-deprecations.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/50-arrayiterator-deprecations/arrayiterator-deprecations.php
arrayiterator-deprecations.php
<?php
declare(strict_types=1);
$inventory = new ArrayObject(['large' => 12, 'small' => 3, 'medium' => 7]);
$inventory->asort();
foreach ($inventory->getIterator() as $size => $count) {
printf("%s %d\n", $size, $count);
}
echo json_encode($inventory->getArrayCopy(), JSON_THROW_ON_ERROR), PHP_EOL;
small 3
medium 7
large 12
{"small":3,"medium":7,"large":12}

Use ArrayObject for the collection’s sorting and flags or use array functions and create a new iterator when needed. The affected methods are getFlags(), setFlags(), asort(), ksort(), uasort(), uksort(), natsort(), natcasesort(), serialize(), and unserialize(). For application-owned data, store the underlying array or another explicit data format.

Sort by keys using ksort() on the collection. Check that the keys are preserved when you iterate.

Continue with Account for Form Feeds in trim().