Home > other >  Updating deprecated code, from each() to foreach()
Updating deprecated code, from each() to foreach()

Time:05-24

I'm working to fix some old code that triggers a warning on PHP 7.2.0, beacause each() is deprecated.

I tried to replace each() with foreach() like the following, but it doesn't work. I found some answers on StackOverflow, but none with a straight pure return as in the old code I'm trying to fix.

Old code that needs to be updated (works well, but triggers a warning):

if ($n > 0){
    if ($n !== count($array)){
        return (bool) each($array);
    }
}

What I tried (and doesn't work):

if ($n > 0){
    if ($n !== count($array)){
        foreach($array as $key => $value) {
            return (bool) $value;
        }
        unset($value);
    }
}

Any help is appreciated, thank you :)

CodePudding user response:

It seems like the php team encourages you to manage array pointers yourself. you can replace the original array with an ArrayIterator wrapper.

$arrayItor = new ArrayIterator($array);

Then your code can be updated by using this iterator.

if ($n > 0){
    if ($n !== $arrayItor->count()){
        $ret = $arrayItor->current();
        $arrayItor->next();
        return (bool)$ret;
    }
}

Another approach is current and next are not deprecated yet, so you can use them to replace the each function

if ($n > 0){
    if ($n !== count($array)){
        $ret = current($array);
        next($array);
        return (bool)$ret;
    }
}
  • Related