ExpertRefresh

Basics / Reference  

1) What is the value of the array? <?php $arr = array(1,2,3,4); foreach ($arr as $val) { $val *= 2; } foreach ($arr as &$val) { $val *= 2; }





2) What will be the output? <?php $a = 1; $b = &$a; $a = 2; echo $b;






Variables are not passed by reference (& needed) <?php $a = 1; $b = $a; $a = 2; echo $b; // output 1 $a = 1; $b = &$a; // --- Look Here --- // $a = 2; echo $b; // output 2 Reference with foreach changes the array <?php $arr = array('1', '2', '3', '4'); foreach ($arr as $val) { // Without reference $val *= 2; } print_r($arr); // $arr = array('1', '2', '3', '4'); // The array is not changed foreach ($arr as &$val) { // --- With reference --- // $val *= 2; } print_r($arr); // $arr = array('2', '4', '6', '8'); // --- The array is changed --- // Reference with two foreach has unexpected behavior, use it with care <?php $a = array('a', 'b'); foreach ($a as &$v) {} // 1: $a[0] = a / $a[1] = b / $v = a / $a[0] = &$v // 2: $a[0] = a / $a[1] = b / $v = b / $a[1] = &$v print_r($a); // { a, b } foreach ($a as $v) {} // 1: $a[0] = a / $a[1] = &$v / $a[1] = a // 2: $a[0] = a / $a[1] = a / $v = a print_r($a); // { a, a } // --- Look Here --- //


References