Home > Backend Development > PHP Tutorial > How Can I Replace the Deprecated `each()` Function in PHP?

How Can I Replace the Deprecated `each()` Function in PHP?

Susan Sarandon
Release: 2024-12-16 01:25:09
Original
740 people have browsed it

How Can I Replace the Deprecated `each()` Function in PHP?

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);
Copy after login

Update: Utilize key() and current() for value assignment.

$ar = $o->me; // Reset no longer required
$typ = key($ar);
$val = current($ar);
Copy after login
$out = array('me' => array(), 'mytype' => 2, '_php_class' => null);
$expected = each($out);
Copy after login

Update: Employ key() and current() for element retrieval.

$out = array('me' => array(), 'mytype' => 2, '_php_class' => null);
$expected = [key($out), current($out)];
Copy after login
for(reset($broken);$kv = each($broken);) {...}
Copy after login

Update: Introduce a foreach loop with manual key-value assignment.

foreach ($broken as $k => $v) {
     $kv = [$k, $v];
}
Copy after login
list(, $this->result) = each($this->cache_data);
Copy after login

Update: Assign current value directly, with optional next() advancement.

$this->result = current($this->cache_data);
Copy after login
// 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++;
}
Copy after login

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template