How to update code that uses the deprecated each() function
P粉883223328
2023-08-22 11:44:11
<p>With PHP 7.2, the <code>each</code> function has been deprecated. The documentation mentions: </p>
<blockquote>
<p><strong>Warning</strong> As of PHP 7.2.0, this function has been deprecated. Reliance on this function is strongly discouraged. </p>
</blockquote>
<p>How do I update my code to avoid using it? Here are some examples: </p>
<ol>
<li>
<pre class="brush:php;toolbar:false;">$ar = $o->me;
reset($ar);
list($typ, $val) = each($ar);</pre>
</li>
<li>
<pre class="brush:php;toolbar:false;">$out = array('me' => array(), 'mytype' => 2, '_php_class' => null);
$expected = each($out);</pre>
</li>
<li>
<pre class="brush:php;toolbar:false;">for(reset($broken);$kv = each($broken);) {...}</pre>
</li>
<li>
<pre class="brush:php;toolbar:false;">list(, $this->result) = each($this->cache_data);</pre>
</li>
<li>
<pre class="brush:php;toolbar:false;">// iterating to the end of an array or a limit > the length of the array
$i = 0;
reset($array);
while( (list($id, $item) = each($array)) || $i < 30 ) {
// code
$i;
}</pre>
</li>
</ol>
<p>When I execute the code on PHP 7.2, I receive the following error: </p>
<blockquote>
<p>Deprecated: The each() function has been deprecated. This message will be ignored on further calls</p>
</blockquote><p><br /></p>
2019 Instant Upgrade
each()
There are actually many situations where
each()
can be replaced, which is why there are so many different upvoted answers in this question.besides:
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.4 Steps to Upgrade Your Code
1. Installation
2. Create
rector.php
Configuration file3. Add
PHP_72
Collection4. Run it on your code
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.
For your first two example cases, you can use
key()
andcurrent()
to assign the values you need.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.For the fourth case, the key seems to be ignored in
list()
so you can assign the current value.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 usingnext()
.The fifth case can be replaced by
for()
loop.