MemoryRefresh!

Basics / Reference   Reference



Questions Answers 0%

Pages   0 from 91
Questions   0 from 142

Reset


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 --- // phpf schlueters.de
1) What will be the output? <?php $a = 1; $b = &$a; $a = 2; echo $b;




2) 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; }








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 --- // phpf schlueters.de

References









Programming

Php
   
Regex
   
MySQL
   
Css
   
jQuery
   
Git
   


References