Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
$test = new ArrayIterator(array(1, 2, 3));
$exec = [];
foreach ($test as $l1) {
$exec[] = 'outer ' . $l1;
foreach ($test as $l2) {
$exec[] = 'inner' . $l2;
}
}
var_dump($exec);
@NamelessCoder

This comment has been minimized.

Copy link
Owner Author

commented Jul 14, 2016

array(4) {
  [0] =>
  string(7) "outer 1"
  [1] =>
  string(6) "inner1"
  [2] =>
  string(6) "inner2"
  [3] =>
  string(6) "inner3"
}
@NamelessCoder

This comment has been minimized.

Copy link
Owner Author

commented Jul 14, 2016

http://php.net/manual/en/control-structures.foreach.php sort of explains why, and details a possible difference in PHP 5 and 7. I quote:

As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior.

In PHP 7, foreach does not use the internal array pointer.

http://php.net/manual/en/control-structures.foreach.php

The documentation page originally also stated that:

Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.

Whether that still applies is not certain but from the example above, it would appear so.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.