Abhishek Sanghvi Abhishek Sanghvi -4 years ago 115
PHP Question

Access array using dynamic path

I have an issue in accessing the array in php.

$path = "['a']['b']['c']";
$value = $array.$path;

In the above piece of code I have an multidimensional array named $array.

is a dynamic value which I would get from database.

Now I want to retrieve the value from $array using $path but I am not able to.

$value = $array.$path

returns me


rather than the value.

I hope I have explained my question properly.

Answer Source

You have two options. First (evil) if to use eval() function - i.e. interpret your string as code.

Second is to parse your path. That will be:

//$path = "['a']['b']['c']";
preg_match_all("/\['(.*?)'\]/", $path, $rgMatches);
$rgResult = $array;
foreach($rgMatches[1] as $sPath)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download