Is it safe to add an array to the while loop?

There are numerous questions about the effect of security on manipulating an array when used foreachon it. However, I cannot find any questions about this in the while loop.

So what is interesting, is it safe to do this? The following is an example script in PHP, and I'm not sure if everything is ok.

while ($item = array_pop($array)) {
  findMoreItems($item, $array);
}

function findMoreItems($item, &$array) {
  // Returns null if no more items are found
  $newItem = someFuncFromServer($item);

  if ($newItem) {
    array_push($array, $newItem);
  }
}

For safe, I mean: can I be sure that no items are missing in the loop?

+4
source share
1 answer

Your code is essentially equivalent to:

$item = array_pop($array);
while ($item) {
  findMoreItems($item, $array);
  $item = array_pop($array)
}

function findMoreItems($item, &$array) {
  // Returns null if no more items are found
  $newItem = someFuncFromServer($item);

  if ($newItem) {
    array_push($array, $newItem);
  }
}

, , , , , - , foreach. foreach , , array_pop array_push .

+1

Source: https://habr.com/ru/post/1659192/


All Articles