0

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']"
3
  • Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on Stack Overflow. For more details see Should 'Hi', 'thanks,' taglines, and salutations be removed from posts? Commented Jun 18, 2015 at 23:55
  • your post is confusing. What exactly are you trying to achieve? Commented Jun 19, 2015 at 0:11
  • sorry i don't know how to explain it any better. Basically i need to parse string to variable so i can get the value of variable Commented Jun 19, 2015 at 0:16

1 Answer 1

1

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 . ';');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.