A
A
Andrey Pavlenko2015-12-04 13:00:18
PHP
Andrey Pavlenko, 2015-12-04 13:00:18

PHP7 and foreach. Insidious change?

As the documentation says, in PHP7 foreach now operates on a copy of the array rather than on the array itself.
That is, this code used to work, but now it doesn't (if I'm not mistaken):

<?php
foreach ($arr as $k=>$v)
{
if ($some_condition==$v) {
   unset($arr[$k]);
}
}

Unfortunately, there are some places in the code that use a similar construction.
It turns out that you need to use the project search to find all foreach and replace $k=>$v with $k=>&$v
Will this help?
Or do you need some other way, for example (rewrite to array_filter)?
How should the above code be changed and should it be changed at all?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
O
OnYourLips, 2015-12-04
@Akdmeh

Usually, unsuitable members of the old array are not removed, but a new one is created from suitable ones.

$properElements = [];
foreach ($arr as $k => $v)
{
    if ($some_condition != $v) {
        $properElements[] = $v;
    }
}

R
romy4, 2015-12-04
@romy4

The above code will work fine in php7.

6
65536, 2015-12-04
@65536

in general, it was not worth changing the array from the forycha on it before

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question