ilmansg
ilmansg

Reputation: 99

Access array value using string containing the variable name followed by square-braced key path

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

Answers (1)

userlond
userlond

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

Related Questions