I want to dynamically access value of variable, let’s say I have this array:
$aData = array(
'test' => 123
);
Standard approach to print the test key value would be:
print $aData['test'];
However, if I have to work with string representation of variable (for dynamic purposes)
$sItem = '$aData[\'test\']';
how can I achieve to print aData key named test? Neither of examples provided below works
print $$sItem;
print eval($sItem);
What would be the solution?
Your eval example is lacking the return value:
should do it:
But it’s not recommended to use eval normally. You can go into hell’s kitchen with it because eval is evil.
Instead just parse the string and return the value:
This can be done with some other form of regular expression as well.
As your syntax is very close to PHP an actually a subset of it, there is some alternative you can do if you want to validate the input before using eval. The method is to check against PHP tokens and only allow a subset. This does not validate the string (e.g. syntax and if a variable is actually set) but makes it more strict:
You just give an array of valid tokens to that function. Those are the PHP tokens, in your case those are:
You then just can use it and it works with more complicated keys as well:
I used this in another answer of the question reliably convert string containing PHP array info to array.