Home > Enterprise >  How to get array value to variable from string in PHP?
How to get array value to variable from string in PHP?

Time:03-05

I'm trying to get the value of multi-dimensional array in PHP that is a value of a variable.

The multi-dimensional array has value 12345

$data_array['result']['21']['rich_snippet']['top']['detected_extensions']['reviews'] = "12345";

The array and index(es) are stored as value of a variable $x

$x = "data_array['organic_results']['21']['rich_snippet']['top']['detected_extensions']['reviews'] ";

I expect that echo $$x; will return the value of the array 12345, but i get null

CodePudding user response:

I'm assuming you want to get an array value from a string.

It can be implemented like this:

$data_array['result']['21']['rich_snippet']['top']['detected_extensions']['reviews'] = "12345";
    
$string = "data_array['result']['21']['rich_snippet']['top']['detected_extensions']['reviews']";
    
//Here we escape the $ symbol and substitute our string, then we execute the string through the eval function
$value = eval("return \${$string};"); 
    
echo $value;

Note

The eval function is considered very dangerous, if you receive a string from the user, then you should not trust the data.

  • Related