Pergunta

Can anyone explain me the output of the following PHP script:

        $a = array ('zero','one','two');

        foreach ($a as &$v) {
        }

        foreach ($a as $v) {
        }            

        print_r($a);

Output:

Array ( [0] => zero [1] => one [2] => one )

Foi útil?

Solução 2

Passing by reference, you can change value inside or outside loop.

<?php
        $a = array ('zero','one','two');
        foreach ($a as &$v) {
        }

        // before loop $v is reference to last item in array $a
        // if you perform unset($v) before this loop, nothing will change in $a
        foreach ($a as $v) {
            // here you assigning $v values from this array in loop 
        }            

        print_r($a);
// Array
// (
//     [0] => zero
//     [1] => one
//     [2] => one
// )

Outras dicas

Not really an answer, but it may help you understand what's going on.

<?php

$a = array ('zero','one','two');

foreach ($a as &$v) {
}

print_r($v); // two

$v = "four";

print_r($a);
// Array
// (
//     [0] => zero
//     [1] => one
//     [2] => four
// )
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top