There is a function to which ID $select is passed to the input, and then, at the very beginning of the function body, this number is pushed into the $nextItems . Next, in foriche, I loop through this array, substituting this ID into the query. I process the resulting records in the internal for loop and add their IDs to the same $nextItems using array_push() for subsequent recursion in foric, and after practicing the foric iteration I remove the current ID using array_shift() in the $used line to filter subsequent requests. But the ambush is that the forich works only the first time, although I’m adding new elements to the end of the first iteration.

 $select = 1; $nextItems = []; array_push($nextItems, $select); $visited = ''; foreach ($nextItems as $nextItem){ $query = "SELECT * FROM items WHERE item_x = $nextItem"; for(){ ... ... array_push($nextItems, $newItem); } ... $usedArray = array_shift($nextItems); } 

    1 answer 1

    Trying to change the array that you are going through right now in foreach is a stupid idea. For PHP5, this is undefined behavior; for PHP7, loop traversal is performed on a copy of the array.

    As far as I understand, you are actually trying to make a queue. Accordingly, you need a cycle

     while (! empty($nextItems)) { 

    or, which is equivalent to type reduction, but more compact,

     while ($nextItems) { 

    This is the question why the code behaves wrong. And to the question of what is best to do with this - take the standard SplQueue . Not a reference to the implementation of the queue, but it works much better than copying the entire array again at each iteration (this is array_shift behaves).

    • and a little more detail = for PHP7 - a loop traversal is performed on a copy of the array - and if it changes, are changes only available upon exiting the loop? Or in 7ke you can not just change? - splash58
    • This is about this rfc: wiki.php.net/rfc/php7_foreach Ie in php7, just correct the behavior of the foreach - bypass as in question by value - changes to the original array will not affect the behavior of the cycle, since loop bypasses a copy of the initial array. Bypassing a loop by reference will behave in a more expected way. - Small
    • yeah I read. thank! - splash58