Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 some way without knowing it by name... This would be useful to me in a more complex scenario.

like image 430
dude Avatar asked Sep 22 '10 13:09

dude


1 Answers

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.

like image 166
Artefacto Avatar answered Sep 25 '22 02:09

Artefacto