0

I am trying to pass an index of associative array stored in a variable:

$a = array( 
 'one' => array('one' => 11, 'two' =>12),
 'two' => array('one' => 21, 'two' => 22)
);    
$s = "['one']['two']"; // here I am trying to assign keys to a variable for a future use

echo $a[$s];  // this usage gives error Message: Undefined index: ['one']['two']
echo $a['one']['two']; // this returns correct result (12)

The same I am trying to do within the object:

$a = array( 
 'one' => (object)array('one' => 11, 'two' =>12),
 'two' => (object)array('one' => 21, 'two' => 22)
);
$a = (object)$a; // imagine that I receive this data from a JSON (which has much sophisticated nesting)

$s = 'one->two'; // I want to access certain object property which I receive from somewhere, hence stored in a variable

echo $a->$s;      // produces error. Severity: Notice Message: Undefined property: stdClass::$one->two
echo $a->one->two; // gives correct result ("12")

How do I properly use a variable to access a value as mentioned in above examples? Note: wrapping these into Curly brackets (i.e. complex syntax) did not work in both cases.

djtester
  • 63
  • 4
  • How exactly is this created? User input? `"['one']['two']"` – Andreas Jan 13 '20 at 20:47
  • The value "['one']['two']" is received via REST API (trustful resource) and then passed to a static associative array to retrieve a corresponding value. – djtester Jan 13 '20 at 21:08

2 Answers2

0

I assume you manually typed the ['one']['two'] part and there is no reason for it to look like that.

The by far simplest method is to explode the array indexes and loop them and that way "dig" in to the array.

$a = array( 
 'one' => array('one' => 11, 'two' =>12),
 'two' => array('one' => 21, 'two' => 22)
);    
$s = "one,two";

$res = $a;
foreach(explode(",", $s) as $item){
    $res = $res[$item];
}

echo $res; // in this case echo works. But you should perhaps have if array print_r

https://3v4l.org/LeUFW

If you actually do have the one two like that then you can make it an array like this:

$s = "['one']['two']";
$s = explode("][", str_replace("'", "", trim($s, "[]")));
// $s is now an array ['one', 'two']

https://3v4l.org/YUjbn

Andreas
  • 23,610
  • 6
  • 30
  • 62
-1

The only solution seems to be eval() IF you trust the contents of $s:

eval( 'echo $a'.$s.';' );
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77