Question

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 )

Was it helpful?

Solution 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
// )

OTHER TIPS

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
// )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top