Created
January 26, 2011 20:29
-
-
Save cbandy/797383 to your computer and use it in GitHub Desktop.
Demo copying references within array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
error_reporting(E_ALL | E_STRICT); | |
$array = array(); | |
$var = 5; | |
$array[0] =& $var; | |
// visible reference | |
#var_dump($array); | |
$clone = $array; | |
// clone has reference | |
#var_dump($clone); | |
function param_value($param) | |
{ | |
// parameter has reference | |
var_dump($param); | |
} | |
#param_value($clone); | |
$original = array(); | |
$var_one = 'a'; | |
$original[0] =& $var_one; | |
$original[1] = 'b'; | |
$second = array(); | |
$var_two = 'c'; | |
$second[0] =& $var_two; | |
$second[1] = 'd'; | |
// Works for reference, but not value | |
#$mapped['$1'] =& $original[0]; | |
#$mapped['$2'] =& $original[1]; | |
// Works for reference and value | |
$mapped = $original; | |
$mapped['$1'] =& $mapped[0]; unset($mapped[0]); | |
$mapped['$2'] =& $mapped[1]; unset($mapped[1]); | |
// Still works for reference and value | |
$appended = $second; | |
$mapped['$3'] =& $appended[0]; unset($appended[0]); | |
$mapped['$4'] =& $appended[1]; unset($appended[1]); | |
$var_one = 'y'; | |
$var_two = 'z'; | |
#var_dump($original, $second, $mapped); | |
function append($incoming, & $result) | |
{ | |
$duplicate = $incoming; | |
foreach (array_keys($incoming) as $key) | |
{ | |
$result['$'.(count($result) + 1)] =& $duplicate[$key]; | |
unset($duplicate[$key]); | |
} | |
} | |
$output = array(); | |
append($original, $output); | |
append($second, $output); | |
var_dump($original, $second, $output); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment