Instantly share code, notes, and snippets.

Embed
What would you like to do?
Copy-on-write vs. reference
<?php
echo "\nCopy-on-write:\n";
$a = array(array("result" => "a"));
for ($i=0; $i < 2; $i++) {
foreach ($a as $j => $v) {
$v["result"] .= "a";
echo $v["result"] ."\n";
}
}
foreach ($a as $k => $v) echo $v["result"] ."\n";
echo "\nBy reference:\n";
$b = array(array("result" => "b"));
for ($i=0; $i < 2; $i++) {
foreach ($b as $j => &$v) {
$v["result"] .= "b";
echo $v["result"] ."\n";
}
}
foreach ($b as $k => $v) echo $v["result"] ."\n";
echo "\nDirect array index:\n";
$c = array(array("result" => "c"));
for ($i=0; $i < 2; $i++) {
foreach ($c as $j => $v) {
$c[$j]["result"] .= "c";
echo $c[$j]["result"] ."\n";
}
}
foreach ($c as $k => $v) echo $v["result"] ."\n";
echo "\nObject:\n";
$obj->result = "d";
$d = array($obj);
for ($i=0; $i < 2; $i++) {
foreach ($d as $j => $v) {
$v->result .= "d";
echo $v->result ."\n";
}
}
foreach ($d as $k => $v) echo $v->result ."\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment