Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save NamelessCoder/92b9a74b5c0f81b34ddcc42826614442 to your computer and use it in GitHub Desktop.
Save NamelessCoder/92b9a74b5c0f81b34ddcc42826614442 to your computer and use it in GitHub Desktop.
<?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
Copy link
Author

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

@NamelessCoder
Copy link
Author

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