I have an array $arr = ['a', ['b',['c','d','e']]];
.
So $arr[1][1][0]
is 'c'
.
I have these indexes listed in n array: $idx = [1,1,0];
(this may sound tricky, but comes from the fact that I got them from parsing a kind of scripting pseudo-language).
I have a recursive function which returns a reference to the expected element:
function &getDeepRef(&$array, $indexes){...}
Usage:
$ref = & getDeepRef($arr, $idx);
At that point, everything works as expected:
echo $ref;
===> outputs 'c'
$ref = 12;
print_r($arr);
==> $arr
is now ['a', ['b',[12,'d','e']]]
Here comes my question:
I need $arr[1][1][0]
to become a reference to another variable $otherVar
.
Can I do this using the $ref
reference?
If yes, I couldn’t find the right syntax for this
($ref = &$OtherVar;
unsets $ref
as a reference to $arr[1][1][0]
, and makes it a reference to $otherVar
, but in no way helps make $arr[1][1][0]
a reference to $otherVar
).
If no, how would you make the array element which indexes are listed in an array, become a reference to a given variable?
[Edit]
I found a solution based on eval();
, but I’d rather use another way for security reasons:
$arr = ['a', ['b', 'ii'=> ['c','d','e']],'f'];
out($arr);
$idxLeft = [2];
$idxRight = [1,'ii',0];
$ref = &getDeepRef($arr,$idxRight);//$ref now is a reference to $arr[1]['ii'][0]
$ref = 'ccc';//demo: $arr[1]['ii'][0] is now 'ccc'
out($arr);
//Now the target: $arr[2] = &$arr[1]['ii'][0];
//Following does NOT work:
$leftRef = &getDeepRef($arr,$idxLeft);
$rightRef = &getDeepRef($arr,$idxRight);
$leftRef = &$rightRef; //this did NOT make $arr[2] a reference to $arr[1]['ii'][0]
//instead it broke the reference from $leftRef on $arr[2] and made a new reference from $leftRef onto $arr[1]['ii'][0].
//Following DOES work, but I'd prefer avoiding eval(); [notice: the mapping with json_encode is just here for string indexes compatibility, like 'ii']
$eval = '$arr['. implode('][',array_map('json_encode',$idxLeft)) . '] = &$arr['. implode('][',array_map('json_encode',$idxRight)) . '];';
out($eval);
eval($eval);
out($arr);
$a = &getDeepRef($arr,$idxLeft);
$a=45;
out($arr);
function &getDeepRef(&$var,$indexes){//third param just for exception message
if(null===($id=array_shift($indexes))){ return $var; }
if(!is_array($var) || !array_key_exists($id, $var)){ throw new Exception("Bad key: [$id]"); }
return getDeepRef($var[$id],$indexes);
}
function out($v){
static $i=0;
echo '<br>'.++$i.' - '; print_r($v);
}