Memory App
Programming
 




In PHP

In PHP variables are NOT passed by reference (& needed)

$a = 1; 
$b = $a; 
$a = 2;

echo $b; // 1

$a = 1; 
$b = &$a;
$a = 2;

echo $b; // 2
(1/3)

Array changed

Reference with foreach changes the array

$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 --- //
(2/3)

Unexpected behavior

Reference with two foreach has unexpected behavior, use it with care:

$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 --- //
http://schlueters.de/blog/archives/141-References-and-foreach.html

Questions



Top Reference > Programming