Wednesday 5 September 2018

PHP Any way to access the array element with a variable concatenation

Is there anyway to access array "$a" given a variable with a string path through array "$a"?
For example:
$b = "['one']['1.1']";
$a = array(
    'one' => array(
        '1.1' => 'One point One',
        '1.2' => 'One point Two',
    ),
    'two' => array(
        '2.1' => 'Two point One',
        '2.2' => array(
            '2.2.1' => 'Two point Two point One',
        ),
    ),
);

echo ${$a.$b};

I have attempted ${$a.$b} and several other variations, any suggestions?

You can use eval for this purpose. However, please be wary that there is probably a better way to do what your doing and anything put into eval() should be well sanitized.
eval("echo \$a$b;");

0 comments:

Post a Comment