This referencing works:
$awesome_array = array (1,2,3);
$cool_array = array (4,5,6);
$ref = &$awesome_array; // reference awesome_array
$awesome_array = $cool_array;
echo $ref; //produces (4,5,6) as expected
This referencing also works:
$array[0] = "original";
$element_reference = &$array[0]; // reference $array[0]
$array[0] = "modified";
echo $element_reference; // returns "modified" as expected.
But referencing the elements in an array does not work when you change the entire array. How do you get around this?
$array = array (1,2,3);
$new_array = array (4,5,6);
$element_reference = &$array[0]; // reference $array[0]
$array = $new_array; // CHANGE ENTIRE ARRAY
echo $element_reference; // returns 1 despite the fact that the entire array changed. I need it to return 4?
Why does it not return 4 since the array has changed? How do you reference the element so it returns 4?
The reference is to an element in the array, and not to "an index into a variable called $array
". As such, none of the references (for elements in the old array) apply to the new array.
The original references still refer to the original array, and elements therein; even if the original array is no longer immediately accessible.
To refer a particular index of a variable that resolves to an array, just use a normal index operation:
$array = array (1,2,3);
$new_array = array (4,5,6);
$i = 0;
echo $array[$i]; // -> 1
$array = $new_array; // reassign variable with new array
echo $array[$i]; // -> 4