Updating Code to Avoid Using the Deprecated each() Function
The each() function has been officially deprecated in PHP 7.2, prompting the need for code updates to avoid errors and maintain best practices. This article provides guidance on how to modernize code that currently employs each().
Sample Code and Solutions:
Consider the following code excerpts and their corresponding updates:
$ar = $o->me; reset($ar); list($typ, $val) = each($ar);
Update: Utilize key() and current() for value assignment.
$ar = $o->me; // Reset no longer required $typ = key($ar); $val = current($ar);
$out = array('me' => array(), 'mytype' => 2, '_php_class' => null); $expected = each($out);
Update: Employ key() and current() for element retrieval.
$out = array('me' => array(), 'mytype' => 2, '_php_class' => null); $expected = [key($out), current($out)];
for(reset($broken);$kv = each($broken);) {...}
Update: Introduce a foreach loop with manual key-value assignment.
foreach ($broken as $k => $v) { $kv = [$k, $v]; }
list(, $this->result) = each($this->cache_data);
Update: Assign current value directly, with optional next() advancement.
$this->result = current($this->cache_data);
// 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++; }
Update: Utilize a for loop for traversal with manual key-value retrieval.
reset($array); for ($i = 0; $i < 30; $i++) { $id = key($array); $item = current($array); // code next($array); }
By implementing these updates, you can effectively modernize your code and align it with current PHP standards.
The above is the detailed content of How Can I Replace the Deprecated `each()` Function in PHP?. For more information, please follow other related articles on the PHP Chinese website!