Upgrading Code from the Deprecated each() Function
PHP 7.2 has deprecated the each() function, causing warnings when using it. This article explores how to modernize your code and avoid using each().
Sample Cases
Here are several examples where each() was previously employed:
Assigning values with reset() and list():
$ar = $o->me; reset($ar); list($typ, $val) = each($ar);
Assigning values directly:
$out = array('me' => array(), 'mytype' => 2, '_php_class' => null); $expected = each($out);
Iterating through an array incorrectly:
for(reset($broken);$kv = each($broken);) {...}
Ignoring the key in a list() assignment:
list(, $this->result) = each($this->cache_data);
Iterating incorrectly with length checks:
reset($array); while( (list($id, $item) = each($array)) || $i < 30 ) { // code $i++; }
Updated Code
1. Assigning Values
Replace with key() and current():
$ar = $o->me; $typ = key($ar); $val = current($ar);
2. Direct Assignment
Replace with an explicit array key and value:
$out = array('me' => array(), 'mytype' => 2, '_php_class' => null); $expected = [key($out), current($out)];
3. Correct Iteration
Use foreach() and assign the key-value pair inside the loop:
foreach ($broken as $k => $v) { $kv = [$k, $v]; }
4. Key Disregard
Assign the current value directly:
$this->result = current($this->cache_data);
5. Array Iteration with Checks
Replace with a traditional for() loop:
reset($array); for ($i = 0; $i < 30; $i++) { $id = key($array); $item = current($array); // code next($array); }
The above is the detailed content of How to Replace PHP's Deprecated `each()` Function?. For more information, please follow other related articles on the PHP Chinese website!