-1

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 )
proseosoc
  • 1,168
  • 14
  • 23

2 Answers2

2

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

Gregoire Ducharme
  • 1,095
  • 12
  • 24
1

found that in PHP you can't reference to reference. found with this code:

$val = 'OOOOOO';
$b = 'DEFAULT';

$bb = &$b;
$bb = &$val;

echo $b; // prints: DEFAULT

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):

Tested 5 times using Approach 3 (By Reference):

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

Tested 5 times using Approach 4 (By Value):

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

proseosoc
  • 1,168
  • 14
  • 23