开发者

Foreach Iterator Behavioral Difference in PHP 5.2.0 versus PHP 5.3.3

开发者 https://www.devze.com 2023-03-16 09:36 出处:网络
开发者_JS百科$test = array(1, 2, 3, 4, 5); foreach($test as $element) { echo $element; $element = next($test);
开发者_JS百科$test = array(1, 2, 3, 4, 5);


foreach($test as $element)
{
    echo $element;        
    $element = next($test);         
    echo $element;
}

This produces the output "122334455" in PHP 5.2.0 The output "13243545" is produced in PHP 5.3.3

How do I reproduce the output of 5.2.0 in 5.3.3 most efficiently by means of controlling the iterator?

This may be a bug as the iterator works in 5.2 inside the foreach, but not in 5.3's foreach.


It seems a bug related with PHP. You can use a more explanatory "for" loop:

$c = count($test);

for($i=0; $i < $c; $i++) {
    echo $test[$i];
    if(isset($test[$i+1])) {
        echo $test[$i+1];
    } else {
        echo $test[$i];
    }
}


My try:

$i = 1;
foreach($test as $element)
{
    echo $element;
    if (isset($test[$i])) {      
        $element = $test[$i];         
        echo $element;
    }

    $i++;
}

This also works but is memory inefficient :

$test  = array(1, 2, 3, 4, 5);
$test2 = $test;

foreach($test as $element)
{
    echo $element;        
    $element = next($test2);         
    echo $element;
}


Dunno what you are asking.. anyway:

echo array_shift($test);
foreach($test as $v) {
 echo $v.$v;
}

prints: 122334455 as asked in the original question

0

精彩评论

暂无评论...
验证码 换一张
取 消