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

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

Barbara Streisand
Barbara StreisandOriginal
2024-12-20 15:01:11758browse

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);
  2. Assigning values directly:

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

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

    list(, $this->result) = each($this->cache_data);
  5. 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!

Statement:
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