PHP: can one determine the parent array's name and key from a reference to an array element?
let's assume we have an array like this
$arr=array(array('a'=>1,'b'=>2),array('c'=>3,'d'=>4));
and a reference to one of its elements
$element=&$arr[1]['c'];
My question is is it possible to get back to the original array using the reference alone? That is to get back to the parent array in so开发者_如何学Pythonme way without knowing it by name... This would be useful to me in a more complex scenario.
No, it's certainly not possible. Being a "reference" (as PHP calls it; it's actually a copy inhibitor) doesn't help at all in that matter. You'll have to store the original array together with the element.
$elArrPair = array(
"container" => $arr,
"element" => &$arr[1]['c'],
);
This way you can change the element with $elArrPair["element"] = $newValue
and still be able to access the container.
You cannot get from $element
to $arr
. You can use in_array()
of course, but nothing about $element
contains a reference to $arr
.
You copy the contect from one variable to another, nothing else, there is no connection between the two variables.
精彩评论