Search code examples
phparraysphp-8spl

PHP8 - SplFixedArray iterator's next() doesn't move key pointer


Please take a look at this code:

<?php

  $array = new SplFixedArray(1);

  print "\nKey1: " . $array->getIterator()->key();

  $array->setSize(5);
  $array->getIterator()->next();
  $array->getIterator()->next();
  $array->getIterator()->next();

  print "\nKey2: " . $array->getIterator()->key() . "\n";

/*
  Result (PHPv8.1.5): 

  Key1: 0
  Key2: 0
*/

Am I right that in this case Key1 and Key2 shouldn't be the same (0) but moved from 0 (key1) to 3 (key2)? In PHP8 using splFixedArray they forced to use iterator so it's now nested loops-safe. But iterating by ->next() seems... not to iterate. So the pointer is still at the position 0.

Is it PHP8's bug or my code is wrong?

Thank you.


Solution

  • It is not any bug from PHP's side. It works as expected. The issue is with your code.

    $array->getIterator()
    

    The above line will always return a new instance of the iterator. It doesn't follow any singleton pattern to return the same instance each time. So, if you wish to move the internal pointers with iterators and print values, collect the instance in a variable and use the same variable to call next() each time like below:

    <?php
    
      $array = new SplFixedArray(1);
    
      print "\nKey1: " . $array->getIterator()->key();
    
      $array->setSize(5);
      
      $it = $array->getIterator();
      $it->next();
      $it->next();
      $it->next();
    
      print "\nKey2: " . $it->key() . "\n";
    

    Online Demo