Home > Blockchain >  How to get values of array that is value of a variable, in PHP?
How to get values of array that is value of a variable, 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'] ";

Expected

echo $$x;

that gives

12345

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