Home > OS >  Why Reference to Reference Not Working Inside Foreach Loop?
Why Reference to Reference Not Working Inside Foreach Loop?

Time:11-20

In below code if I uncomment(use) Approach 2 & comment(disable) Approach 1, why Approach 2 is not modifying the $arr? What is are the alternatives to Approach 2?

$val = 'OOOOOO';
$arr = ['a' => 'AAA', 'b' => 'BBB'];

echo print_r($arr, true) . '<br>'; //Array ( [a] => AAA [b] => BBB )


// Approach 1 start - THIS WORKS
$arr['a'] = &$val;
$arr['b'] = &$val;
// Approach 1 end

// Approach 2 start - DOES NOT WORKS
// foreach ($arr as $ky => &$vl) {
//     $vl = &$val;
// }
// Approach 2 end

echo print_r($arr, true) . '<br>'; //Array ( [a] => OOOOOO [b] => OOOOOO )

CodePudding user response:

In the foreach loop you can't modifiy your $vl without a reference. Since it's not the original variable.

In PHP (>= 5.0), is passing by reference faster?

What you can do is something like this:

foreach ($array as $key => $value) { 
  /* your condition*/
  $array[$key] = $some_value;
}

Therefore in the foreach you can use $value (that can be modified without consequences) but you can also modify directly your array. Modifications that would be kept outside of the foreach

CodePudding user response:

Found solution for me: Approach 3

Approach 3 (pass by reference foreach loop) is faster than Approach 4 (pass by value foreach loop) (same as Gregoire Ducharme answer):

// Approach 3 start
foreach ($arr as $ky => &$vl) {
    $arr[$ky] = &$val;
}
// Approach 3 end

// Approach 4 start
foreach ($arr as $ky => $vl) {
    $arr[$ky] = &$val;
}
// Approach 4 end

Performance Data (tested on array with long text, 1000000 loops):

By Reference (Approach 3):

Time: 0.32825803756714, Memory Peak Usage: 596672

Time: 0.33496713638306, Memory Peak Usage: 596672

Time: 0.33242797851562, Memory Peak Usage: 596672

Time: 0.35326600074768, Memory Peak Usage: 596672

Time: 0.33251810073853, Memory Peak Usage: 596672

By Value (Approach 4):

Time: 0.36558699607849, Memory Peak Usage: 596672

Time: 0.38936495780945, Memory Peak Usage: 596672

Time: 0.42887806892395, Memory Peak Usage: 596672

Time: 0.44330382347107, Memory Peak Usage: 596672

Time: 0.49368786811829, Memory Peak Usage: 596672

  •  Tags:  
  • php
  • Related