Reputation: 99
How do I parse string of array so I can get the value of variable
sample string
$str = 'prices[holiday:waterpark][person:1_person]';
sample variable
$prices['holiday:waterpark']['person:1_person'] = 100;
I have tried using variables.variable way in php like this
$prices['holiday:waterpark']['person:1_person'] = 100;
$str = "prices\['holiday:waterpark'\]\['person:1_person'\]";
$str = str_replace('\\', '', $str);
echo $$str;
but that's not working and I get an error
"Undefined variable: $prices['holiday:waterpark']['person:1_person']"
Upvotes: 0
Views: 76
Reputation: 3818
Try this
<?
$prices['holiday:waterpark']['person:1_person'] = 100;
$str = "prices\['holiday:waterpark'\]\['person:1_person'\]";
$str = stripslashes($str);
// be careful with passing $str from untrusted source
// make necessary variable filtering before!
echo eval('return $' . $str . ';');
Upvotes: 1