views:

43

answers:

3

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.

A: 

You cannot get from $element to $arr. You can use in_array() of course, but nothing about $element contains a reference to $arr.

Scott Saunders
+4  A: 

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.

Artefacto
+1 for the container array, interesting technique
Mark Baker
A: 

You copy the contect from one variable to another, nothing else, there is no connection between the two variables.

Hannes
There most certainly *can be* a "connection". `$b['proof'] = $a = 'see?' print $b['proof'];`. Now, that doesn't mean you can ever *know* that `$a` is also being referred to as `$b['proof']`, but there's an obvious link between the two.
cHao
well, if only that would have been what this question was about, clearly you can save a reference in an Element of an array, or any other variable, and access the content of the variable the reference points to ...
Hannes
Not just access. *Change*. The two variables basically become names for the same object. To say "there is no connection" is oversimplifying in the extreme.
cHao