1.2.473. Foreach Don’t Change Pointer

foreach() loops use their own internal cursor.

A foreach loop won’t change the internal pointer of the array, as it works on a copy of the source. Hence, applying array pointer’s functions such as current() or next() to the source array won’t have the same behavior in PHP 5 than PHP 7.

This only applies when a foreach() by reference is used.

<?php

$numbers = range(1, 10);
next($numbers);
foreach($numbers as &$number){
    print $number;
    print current($numbers)."\n"; // Always
}

?>

See also foreach no longer changes the internal array pointer.

1.2.473.1. Connex PHP features

1.2.473.1.1. Suggestions

  • Do not change the pointer on the source array while in the loop

1.2.473.1.2. Specs

Short name

Php/ForeachDontChangePointer

Rulesets

All, Changed Behavior, CompatibilityPHP70

Exakat since

0.8.4

PHP Version

With PHP 7.0 and older

Severity

Major

Time To Fix

Slow (1 hour)

Changed Behavior

PHP 7.0

Precision

High

Available in

Entreprise Edition, Exakat Cloud