Home > Backend Development > PHP Tutorial > How to Replace PHP's Deprecated `each()` Function?

How to Replace PHP's Deprecated `each()` Function?

Barbara Streisand
Release: 2024-12-20 15:01:11
Original
797 people have browsed it

How to Replace PHP's Deprecated `each()` Function?

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:

  1. Assigning values with reset() and list():

    $ar = $o->me;
    reset($ar);
    list($typ, $val) = each($ar);
    Copy after login
  2. Assigning values directly:

    $out = array('me' => array(), 'mytype' => 2, '_php_class' => null);
    $expected = each($out);
    Copy after login
  3. Iterating through an array incorrectly:

    for(reset($broken);$kv = each($broken);) {...}
    Copy after login
  4. Ignoring the key in a list() assignment:

    list(, $this->result) = each($this->cache_data);
    Copy after login
  5. Iterating incorrectly with length checks:

    reset($array);
    while( (list($id, $item) = each($array)) || $i < 30 ) {
     // code
     $i++;
    }
    Copy after login

Updated Code

1. Assigning Values

Replace with key() and current():

$ar = $o->me;
$typ = key($ar);
$val = current($ar);
Copy after login

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

3. Correct Iteration

Use foreach() and assign the key-value pair inside the loop:

foreach ($broken as $k => $v) {
     $kv = [$k, $v];
}
Copy after login

4. Key Disregard

Assign the current value directly:

$this->result = current($this->cache_data);
Copy after login

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

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!

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