P粉4634184832023-08-23 09:19:01
each()
There are actually many situations where each()
can be replaced, which is why there are so many different upvoted answers in this question.
-while (list($key, $callback) = each($callbacks)) { +foreach ($callbacks as $key => $callback) { // ... }
besides:
-while (list($key) = each($callbacks)) { +foreach (array_keys($callbacks) as $key) { // ... }
You can replace them one by one manually. But isn't there a better way?
I help with migration projects and have over 150 cases like this. I'm lazy, so I made a tool called Rector that can convert the code into the above way (there are more cases, but I don't want to spam the answer) .
It is part of the PHP_72
collection.
composer require rector/rector --dev
rector.php
Configuration filevendor/bin/rector init
PHP_72
Collection<?php use Rector\Core\Configuration\Option; use Rector\Set\ValueObject\SetList; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; return static function (ContainerConfigurator $containerConfigurator): void { $parameters->set(Option::SETS, [ Setlist::PHP_72, ]); };
vendor/bin/rector process src --set php72
Hope it helps with your migration.
If there are any errors or exceptions, that's what Rector missed. Create an issue so we can fix it and make it work for all possible cases.
P粉9828815832023-08-23 00:06:26
For your first two example cases, you can use key()
and current()
to assign the values you need.
$ar = $o->me; // 重置不是必需的,因为你刚刚创建了数组 $typ = key($ar); $val = current($ar);
$out = array('me' => array(), 'mytype' => 2, '_php_class' => null); $expected = [key($out), current($out)];
In these cases you can use next()
to advance the cursor afterwards, but this may not be necessary if the rest of your code does not rely on it.
For the third case, I suggest you just use a foreach()
loop and allocate $kv
inside the loop.
foreach ($broken as $k => $v) { $kv = [$k, $v]; }
For the fourth case, the key seems to be ignored in list()
so you can assign the current value.
$this->result = current($this->cache_data);
Like the first two cases, depending on how the rest of your code interacts with $this->cache_data
, you may need to advance the cursor using next()
.
The fifth case can be replaced by for()
loop.
reset($array); for ($i = 0; $i < 30; $i++) { $id = key($array); $item = current($array); // 代码 next($array); }