1

I got a string var named: $taxonomy_str

For example, echo $taxonomy_str will display:

array('relation' => 'AND', 
  array('taxonomy' => category, 
        'field' => 'id', 
        'terms' => array( 41, 42 ), 
        'operator' => 'IN'), 
  array('taxonomy' => geography,
        'field' => 'id',
        'terms' => array( 20, 29 ),
        'operator' => 'IN')
)

I need a way to convert this string with an array statement into a real array, how can I achieve this using PHP?

Thanks.

6
  • 2
    How is this variable being generated? The answer to your question would be eval(), but 999 times out of 1000 there is a safer and more elegant alternative to accomplish what you want before you have to resort to eval(). Commented Nov 30, 2011 at 22:18
  • eval = evil. Just dont do it! Commented Nov 30, 2011 at 22:26
  • not even eval can match this beast Commented Nov 30, 2011 at 22:32
  • Yes the string is generated and sanitized in a really safe way. Could You provide an example please? Commented Nov 30, 2011 at 22:37
  • serialize() and unserialize() OR use combinations of json_encode() and json_decode() Commented Nov 30, 2011 at 22:49

4 Answers 4

4

A somewhat trivial thing to do is simply eval:

eval('$foo = ' . $taxonomy_str . ';');
// $foo now contains the outer array

(from the comments) maybe better form:

$foo = eval('return ' . $taxonomy_str . ';');

This literally executes $taxonomy_str as if it were source, so any valid PHP provided as input will run. There's a certain level of danger here if you were to say, take $taxonomy_str as input from a user.

Sign up to request clarification or add additional context in comments.

3 Comments

Assuming the input string is trustworthy, this is good. If it has any potential to come from the user at all, this is a horrible, horrible idea. I'm not going to up or downvote this, because it really all depends on where the variable comes from. If the variable can be totally trusted, this is a good solution
Actually, you would need eval("return $taxonomy_str;").
@NullUserException Too late in the day. I didn't properly read the example. Although I would personally use $foo = eval("return $taxonomy_str;");.
4

You can use eval(), but it's really not safe if you take your string from the user input.

Comments

1

You can use eval() function. For more information look in PHP official documentations

Comments

1

You can use the eval function. Make sure your string is safe and has no dodgy stuff.

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.