tags:

views:

60

answers:

2

Example:

foreach ($veryFatArray as $key => $value) {

Will the foreach assign the value behind the $key by reference to $value, or will $value be a copy of what's stored in the array? And if yes, how could I get an reference only? The array values store pretty big amounts of data so copying them is not really good.

+4  A: 

$value will be a copy, but (please someone correct me if I'm wrong here), PHP is actually very smart about pass-by-value type things. It will actually do a pass-by-reference and only copy if you modify the variable. For example:

function foo ($bar) {
    echo $bar['x'];
    // internally, $bar is a reference to $baz. (virtually) no extra memory used
    $bar['y'] = 'Y';
    // only now has the array been copied in memory
}

$baz = array('x' => '1', 'y' => '2');
foo($baz);

In your foreach, if you want to modify the original array, you could do this:

// PHP 4
foreach (array_keys($veryFatArray) as $key) {
    $value =& $veryFatArray[$key];
    // ...
}

// PHP 5
foreach ($veryFatArray as $key => &$value) { }

If you are only reading from $value and not writing to it, then it shouldn't be a problem.

nickf
+4  A: 

Don't try and second-guess the interpreter is the moral of the story here. $value is actually a copy but an efficient copy. PHP uses pass-by-value (for non-objects) but also uses copy-on-write. What this means is that if you write:

foreach ($bigitems as $bigitem) {
  echo $bigitem;    // uses original
  $bigitem = 'foo'; // item copied and assigned 'foo'
  echo $bigitem;    // uses copy
}

Just declare your intent: that you want to use the array values. Let PHP sort it out after that. Basically only use references in the loop like this if you intend to change the array. Otherwise you're sending the wrong message to someone else who reads your code.

Section 1 of Copy-on-Write in the PHP Language should tell you everything you ever wanted to know about PHP copy-on-write.

cletus