3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Collection { public $fixedArray; public function __construct(SplFixedArray $splFixedArray) { $this->fixedArray = $splFixedArray; } public function getSum() { $sum = 0; $arr = $this->fixedArray; foreach ($arr as $item) { $sum += $item; } return $sum; } } $spl = SplFixedArray::fromArray([0, 1, 2]); $collection = new Collection($spl); $collArr = $collection->fixedArray; echo 'Test #1'.PHP_EOL; $i = 0; foreach ($collArr as $item) { echo '-- iteration: ' . $i . ', item: ' . $item .', sum: ' . $collection->getSum() . PHP_EOL; $i++; } echo 'Expected 3 iterations, executed ' . $i . PHP_EOL; echo PHP_EOL; echo 'Test #2'.PHP_EOL; $i = 0; // Note, unless we use $collection->getSum() inside the loop - it works as expected! foreach ($collArr as $item) { echo '-- iteration: ' . $i . ', item: ' . $item . PHP_EOL; $i++; } echo 'Expected 3 iterations, executed ' . $i . PHP_EOL;
Output for 8.0.0 - 8.0.15, 8.1.0 - 8.1.2
Test #1 -- iteration: 0, item: 0, sum: 3 -- iteration: 1, item: 1, sum: 3 -- iteration: 2, item: 2, sum: 3 Expected 3 iterations, executed 3 Test #2 -- iteration: 0, item: 0 -- iteration: 1, item: 1 -- iteration: 2, item: 2 Expected 3 iterations, executed 3
Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.27
Test #1 -- iteration: 0, item: 0, sum: 3 Expected 3 iterations, executed 1 Test #2 -- iteration: 0, item: 0 -- iteration: 1, item: 1 -- iteration: 2, item: 2 Expected 3 iterations, executed 3

preferences:
50.1 ms | 461 KiB | 5 Q