PHP 7.2 deprecated: while = each() loop without $value

Petro Mäntylä picture Petro Mäntylä · Feb 10, 2018 · Viewed 13.8k times · Source

As each() loop is deprecated since PHP 7.2, how to update the below while(() = each()) loop without $value?

Without the $value I can't get foreach loop to work. In addition while($products_id = $this->contents) results in infinite loop.

Thank you!

$total_items = 0;

reset($this->contents);
while (list($products_id, ) = each($this->contents)) {
    $total_items += $this->get_quantity($products_id);
}

Answer

Petro Mäntylä picture Petro Mäntylä · Feb 10, 2018

I found a way to fix it and thought to share the information. Here are also other cases about how to upgrade each() loops to foreach().

Case 1: Missing $value

reset($array);
while (list($key, ) = each($array)) {

Update to:

foreach(array_keys($array) as $key) {

Case 2: Missing $key

reset($array);
while (list(, $value) = each($array)) {

Update to:

foreach($array as $value) {

Case 3: Not missing anything

reset($array);
while (list($key, $value) = each($array)) {

Update to:

foreach($array as $key => $value) {