H
H
Hint2015-09-28 17:18:15
PHP
Hint, 2015-09-28 17:18:15

Nested foreach with one array. Is the result guaranteed?

There is an array, you need to go through all combinations of elements (nested loops over one array). Is it safe to use foreach? The documentation still has information about a pointer that gets lost after foreach. Is there a guarantee that the code will always work the same way? That php7 or some other version won't change behavior?
Stumbled upon an old question: stackoverflow.com/questions/2533249/nested-foreach...
It talks about the problem that nested foreach with a single array doesn't work. Now there is no such problem, but will it pop up again? Is there any information that the old behavior was a bug, and this will not happen again? Or is it better just in case to copy the array in advance and use a copy in the nested foreach?

$a = array('a' => 1, 'b' => 2);
foreach ($a as $k1 => $v1)
{
  foreach ($a as $k2 => $v2)
  {
    echo "{$k1}{$v1}{$k2}{$v2}\n";
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis, 2015-09-28
@Hint

foreach under the hood copies an array if that array is not a reference. (Don't forget the objects)

To say more precisely, foreach statement always makes use of a copy of the given array instead of the original itself unless the array is a reference or has a reference.
https://bugs.php.net/bug.php?id=21702
$a = [1,2];
$b = &$a;
foreach ($b as ...
foreach ($a as &$value)...
In these two cases, you will work with the array "directly", where it will be dangerous to change the pointer. But in any other case,
everything will be fine.
it has its own scope foreach
($a as $b) { };
echo $b; // Error .net/bug.php?id=8353

R
RomkaChev, 2015-09-28
@RomkaChev

Since you have already reached a sufficient level of paranoia foresight, then, judging by what you have already managed to google, you NEED to use copies.
PS Do you understand that you will not be able to sleep peacefully if you do not use a copy? What if your code doesn't work in php8? Maybe use an inner for loop ? What if there is also a problem with pointers? Italian.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question